[leedcode 22] Generate Parentheses

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);
            
        }
        
        
    }
}

 

posted @ 2015-07-07 22:52  ~每天进步一点点~  阅读(114)  评论(0编辑  收藏  举报