1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
   | 
 
 
 
  public class GenerateParentheses {     public List<String> generateParenthesis(int n) {         List<String> result = new ArrayList<String>();         if (n <= 0) {             return result;         }         helper(n, n, new StringBuilder(), result);         return result;     }     private void helper(int left, int right, StringBuilder sb, List<String> result) {         if (left == 0 && right == 0) {             result.add(sb.toString());             return;         }         if (left > right) {             return;         }         if (left > 0) {             StringBuilder sbl = new StringBuilder(sb);             sbl.append('(');             helper(left - 1, right, sbl, result);         }         if (right >= left) {             StringBuilder sbr = new StringBuilder(sb);             sbr.append(')');             helper(left, right - 1, sbr, result);         }     }     @Test     public void test() {         List<String> result = generateParenthesis(3);     } }
 
  |