Wednesday, April 30, 2014

Print all valid combinations of n-pairs of parentheses

For example, if n=1
{}
for n=2
{}{}
{{}}

Most of the solutions found online are using recursion. Here is the version which does iterative. 

The key is to keep track of the number of open parentheses, if there are open ones left, then add it to, also if number of open parentheses is bigger than close ones, then add close parentheses as well.


public static void allParenthesis(int k){
Map<String, Integer> list = new HashMap<String, Integer>();
list.put("(", 1);
for(int i = 1 ; i < k*2; i++){
Map<String, Integer> temp = new HashMap<String, Integer>();
for(String s : list.keySet()){
int left = list.get(s);
int right = s.length() - left;
if(left<k){
temp.put(s + "(", left+1); 
}
if(left>right){
temp.put(s + ")", left);
}
}
list = temp;
}
for(String s: list.keySet())
System.out.println(s);
}

No comments:

Post a Comment