Concise recursive Java solution


  • 0
    Y
    class Solution {
    	List<String> res = new ArrayList<>();
        public List<String> generateParenthesis(int n) {
            helper(0,n,"");
            return res;
        }
        public void helper (int numLeft, int x, String s) {  //x: the remaining () left
        	if (numLeft==0 && x==0) {
        		res.add(s);
        		return;
        	}
        	if (numLeft+1<=x) {
        		helper(numLeft+1, x, s+"(");
        	}
        	if (numLeft>0) {
        		helper(numLeft-1, x-1, s+")");
        	} 	
        }
    }
    

Log in to reply
 

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