括号生成

class Solution {
    List<String> res = new LinkedList<>();
    public List<String> generateParenthesis(int n) {
        if(n == 0) return null;    
        dfs("",0,0,n);
        return res;
    }
    //l:左括号用了几个
    //r:右括号用了几个
    private void dfs(String curStr,int l,int r,int n){
        if(l == n && r == n){
            res.add(curStr);
            return ;
        }
        if(l < r) return ;//不符合题意,构造过程必须是左括号多于等于右括号
        if(l < n){
            dfs(curStr+"(",l+1,r,n);
        }
        if(r < n){
             dfs(curStr+")",l,r+1,n);
        }
    }
}

posted @ 2020-07-28 17:48  浅滩浅  阅读(81)  评论(0编辑  收藏  举报