| 5 | public class QuestionB { |
| 6 | |
| 7 | public static void addParen(ArrayList<String> list, int leftRem, int rightRem, char[] str, int count) { |
| 8 | if (leftRem < 0 || rightRem < leftRem) return; // invalid state |
| 9 | |
| 10 | if (leftRem == 0 && rightRem == 0) { /* all out of left and right parentheses */ |
| 11 | String s = String.copyValueOf(str); |
| 12 | list.add(s); |
| 13 | } else { |
| 14 | if (leftRem > 0) { // try a left paren, if there are some available |
| 15 | str[count] = '('; |
| 16 | addParen(list, leftRem - 1, rightRem, str, count + 1); |
| 17 | } |
| 18 | if (rightRem > leftRem) { // try a right paren, if there�s a matching left |
| 19 | str[count] = ')'; |
| 20 | addParen(list, leftRem, rightRem - 1, str, count + 1); |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | public static ArrayList<String> generateParens(int count) { |
| 26 | char[] str = new char[count*2]; |