Java: brief solution using recursion


  • 1
    H
    public List<String> generateParenthesis(int n)
    {
    	List<String> result = new ArrayList<>();
    	search(result,n,0,0,"");
        return result;
    }
    private static void search(List<String> result, int n, int left, int right, String str)
    {
    	if(left == n && right == n)
    	{
    		result.add(str);
    		return;
    	}
    	if(right > left || left > n) return;
    	search(result, n, left + 1, right, str + "(");
    	search(result, n, left, right + 1, str + ")");
    	return;
    }

Log in to reply
 

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