Easy java solution


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

    }


  • 0
    Y

    can you explain why there is no duplicated in the result?


  • 3

    @yin10 binary tree, no duplicated path


  • 0
    T

    What is the time complexity?


  • 0
    C

    truly a very smart solution


  • 0
    C

    Can anyone tell me the time complexity?


  • 1
    R

    @yin10 The reason why there are no duplicates is because it is based on an unambiguous context-free grammar (if you know what those are):
    S -> S(S) | empty
    Here it is rewritten as in a single function:

    public List<String> ans (int n) {				
    	List<String> parens = new ArrayList<String>();  
    	if (n == 0) parens.add(""); //base case
    	else { // recursive case
    		for (int i = 0; i < n; i++){
    			for ( String front:ans(i))
    				for (String back:ans(n-i-1)) 
    					parens.add( front + 
    							      "(" +  
    							     back + 
    							       ")");
    		}
    	}
    	return parens;
    }
    

Log in to reply
 

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