Easy to understand Java Code


  • 0
            public List<String> ans = new ArrayList<>();
    
    	public void recursive(String s, String cmp, int left, int right) {   
            //string cmp  is used to select valid string
    		if(left > 0)
    			recursive(s + "(", cmp + "(", left - 1, right);
    		if(right > 0 && cmp.length() - 1 >= 0 && cmp.charAt(cmp.length() - 1) == '(') {
    			cmp = cmp.substring(0, cmp.length() - 1);
    			recursive(s + ")", cmp, left, right - 1);
    		}
    		if(left == 0 && right == 0)
    			ans.add(s);
    	}
    	public List<String> generateParenthesis(int n) {
    		if(n > 0)
    			recursive("(", "(", n -1, n);
            return ans;
        }
    

Log in to reply
 

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