其他分享
首页 > 其他分享> > 22. Generate Parentheses

22. Generate Parentheses

作者:互联网

This problem is a typical backtracking solution problem, we need a recursive method as helper, the following is my first solution, which is not very good, because the quick conditions are too many.

 private List<String> res = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        helper(n, "", 0);
        return res;
    }
    
    private void helper(int n, String s, int count){
        if(s.length()>n*2 || count>n||count<0)
            return;
        if(s.length()==n*2&&count==0){
            res.add(s.toString());
            return;
        }
        
        helper(n, s+'(', count+1);
        helper(n, s+')', count-1);
    }

Following is a better solution:

    private List<String> res = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        helper(n, "", 0, 0);
        return res;
    }
    
    private void helper(int n, String s, int left, int right){
        if(s.length()==n*2){
            res.add(s.toString());
            return;
        }
        if(left<n)
           helper(n, s+'(', left+1,right);
        if(left>right)
            helper(n, s+')', left, right+1);
    }

 

标签:Parentheses,return,22,helper,int,res,List,private,Generate
来源: https://www.cnblogs.com/feiflytech/p/15860052.html