第一次博客记录,看了些前辈的回溯法解法
22.给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
public static List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
int left = n;
int right = n;
String s = "";
solve( res,left,right,s );
return res;
}
public static void solve(List<String> res,int left,int right,String s){
if(left>right) {
return;
}
if(left>0) {
solve( res,left-1,right,s+"(" );
}
if(right>0){
solve( res,left,right-1,s+")" );
}
if(left==0&&right==0){
res.add( s );
return;
}
}