Java recursion solution


  • 0
    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> ans = new ArrayList<String>();
            char[] s = new char[n*2];
            helper(ans, 0, n, s);
            return ans;
        }
        
        private void helper(List<String> ans, int index, int left, char[] s){
            if (left == 0){
                for (; index < s.length; index++){
                    s[index] = ')';
                }
                ans.add(new String(s));
                return;
            }
            
            s[index] = '(';
            helper(ans, index + 1, left - 1, s);
            
            if (index + left * 2 < s.length){
                s[index] = ')';
                helper(ans, index + 1, left, s);
            }
        }
    }
    

Log in to reply
 

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