生成括号
给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。
样例
给定 n = 3
, 可生成的组合如下:
"((()))", "(()())", "(())()", "()(())", "()()()"
1 public class Solution { 2 /** 3 * @param n n pairs 4 * @return All combinations of well-formed parentheses 5 */ 6 public ArrayList<String> generateParenthesis(int n) 7 { 8 ArrayList<String> ss = new ArrayList<String>(); 9 ss = print(n, n, ss, 0); 10 return ss; 11 } 12 13 ArrayList<String> print(int i, int j, ArrayList<String> ss, int p) 14 { 15 if (ss.size() == 0) 16 { 17 String s = "("; 18 ss.add(s); 19 i--; 20 } else 21 { 22 ArrayList<String> list = new ArrayList(); 23 if (p == 0) 24 { 25 for (String s : ss) 26 { 27 String s1 = s + "("; 28 list.add(s1); 29 } 30 i--; 31 } else 32 { 33 for (String s : ss) 34 { 35 String s1 = s + ")"; 36 list.add(s1); 37 } 38 j--; 39 } 40 ss = list; 41 } 42 43 ArrayList<String> list = new ArrayList(); 44 if (i > 0) 45 { 46 list.addAll(print(i, j, ss, 0)); 47 } 48 if (i < j && j > 0) 49 { 50 list.addAll(print(i, j, ss, 1)); 51 } 52 if (list.size() == 0) 53 { 54 return ss; 55 } 56 return list; 57 } 58 }