Generate Parentheses

dfs 的一个关键是termination condition

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> res = new ArrayList<String>();
        if(n<1) return res;
        dfs(n,n,res,new String());
        return res;
    }
    private void dfs(int nl, int nr,ArrayList<String> res, String item){
        if(nr<nl) return; // nr>nl not working!!!
        if(nr==0 && nl==0) res.add(item);
        
        if(nl>0)
            dfs(nl-1, nr, res, item+'(');
        if(nr>0)
            dfs(nl, nr-1, res, item+')');
    }
}

 

posted @ 2015-06-02 00:08  世界到处都是小星星  阅读(107)  评论(0编辑  收藏  举报