Simple Java Recursive Solution


  • 1
    S

    left is how many "(" we can add after, right is how many ")" we can add after.

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

Log in to reply
 

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