给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
比较巧妙的解法是,要想到左边的括号必须大于右边的括号,否则就会出现)(的情况,是不合法的。
用递归解决,其中因为temp赋值位置错误+StringBuffer的不慎使用导致结果迟迟不对。
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
String temp = new String();
method(n, n, temp, list);
// System.out.println(list);
return list;
}
//1,r表示剩下的左括号数量和右括号数量
public void method(int l,int r,String temp,List<String> list) {
if(l>r) return;//此时是)(的情况
if(l==0 && r==0) list.add(temp.toString());
else {
if(l>0) {
method(l-1, r, temp+'(', list);
}
if(r>0) {
method(l, r-1, temp+')', list);
}
}
}
}
回溯法简单!!
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if(n==0) return null;
method("", n, 0, 0);
return result;
}
public void method(String nowS,int n,int left,int right) {
if(left+right==2*n) {
result.add(nowS);
return;
}
if(left<n) {
method(nowS+"(", n, left+1, right);
}
if(left>right) {
method(nowS+")", n, left, right+1);
}
}