Simple Java recursive solution


  • 0
    V
    public class Solution {
        List<String> result;
        public List<String> generateParenthesis(int n) {
            result = new ArrayList<>();
            paranthesisHelper(n, n, "");
            return result;
        }
        
        private void paranthesisHelper(int l, int r, String s) {
            if(l == 0 && r == 0) {
                result.add(s+"");
                return;
            }
            if(l > 0) paranthesisHelper(l-1, r, s+"(");
            if(r > l) paranthesisHelper(l, r-1, s+")");
        }
    }
    

Log in to reply
 

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