给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
1 public class T22 { 2 HashSet<String> set = new HashSet<>(); 3 4 public List<String> generateParenthesis(int n) { 5 List<String> list = new ArrayList<>(); 6 getKuoHao(n, list, "", 0,0); 7 return list; 8 } 9 10 private void getKuoHao(int n, List<String> list, String s, int open, int close) { 11 if (s.length() == n * 2) { 12 list.add(s); 13 return; 14 } 15 if (open < n) { 16 getKuoHao(n, list, s + "(", open + 1, close); 17 } 18 if (close < n && close < open) { 19 getKuoHao(n, list, s + ")", open, close + 1); 20 } 21 } 22 }