[leedcode 22] Generate Parentheses
2475 ワード
public class Solution {
// , C2n^n-C2n^n-1
// ,
List<String> res;
StringBuilder seq;
public List<String> generateParenthesis(int n) {
res=new ArrayList<String>();
seq=new StringBuilder();
generate(n,0,0,0);
return res;
}
public void generate(int n,int left,int right,int level){
if(2*n==level){
res.add(seq.toString());
return;
}
if(left<n){
seq.append('(');
generate(n,left+1,right,level+1);
seq.deleteCharAt(level);//
}
if(left>right){
seq.append(')');
generate(n,left,right+1,level+1);
seq.deleteCharAt(level);
}
}
}