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); } } }
时间: 2024-10-29 19:12:12