美文网首页
22. Generate Parentheses

22. Generate Parentheses

作者: wtmxx | 来源:发表于2018-02-08 15:29 被阅读0次

利用递归,只需要满足剩下的左括号数小于等于剩下的右括号数就是合适的解

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> zz = new ArrayList<>();
        if(n==0)return zz;
        addParenthese("",zz,n,n);
        return zz;
    }
    private void addParenthese(String s,List<String> zz,int lnum, int rnum){
        if(lnum>rnum)return;
        if(lnum==0){
            for(int i=0;i<rnum;i++){
                s+=")";
            }
            zz.add(s);
            return;
        }
        addParenthese(s+"(",zz,lnum-1,rnum);
        addParenthese(s+")",zz,lnum,rnum-1);
    }
}

相关文章

网友评论

      本文标题:22. Generate Parentheses

      本文链接:https://www.haomeiwen.com/subject/ukuttftx.html