Easy understanding JAVA recursive solution


  • 3
    S

    The condition you may add left bracket is left > 0, the condition to add right bracket is right > left.

    public class Solution {
        List<String> res = new ArrayList<String>();
        public List<String> generateParenthesis(int n) {
            if(n<=0)    return res;
            helper(n,n,"");
            return res;
        }
        private void helper(int left, int right, String s){
            if(left == 0 && right == 0){
                res.add(s);
                return;
            }
            if(left > 0)
                helper(left-1,right,s+"(");
            if(right >left)
                helper(left,right-1,s+")");
        }
    }

  • 0
    Z

    are you chinese? I want to ask you some question.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.