Thursday, April 14, 2011

All possible bracket combinations

How can we generate all possibilities on braces ?
N value has given to us and we have to generate all possibilities.
**Examples:**
1) if N == 1, then only one possibility () .
2) if N==2, then possibilities are (()), ()()
3) if N==3, then possibilities are ((())), (())(),()()(), ()(()) ...
Note: left and right braces should match. I mean )( is INVALID for the N==1


The below recursion tree shows the flow:





public static void allValidBrackets(int n, int open, int closed, String str) {

if (closed == n) {
System.out.println(str);
return;
}

if (open < n) {
allValidBrackets(n, open+1, closed, str + "{");
}

if (closed < open) {
allValidBrackets(n, open, closed+1, str + "}");
}
}

1 comment:

Guru Prasad G.V. said...

https://github.com/gurugv/algos/blob/master/trest/src/org/guru/string/CurlyBraceCombination.java