JAVA-----------Easy Version To UnderStand!!!!!!!!!!!


  • 0
    H
    public static void DFS(int leftNumber, int rightNumber, StringBuffer s, List<String> result) {
    	if (leftNumber == 0 && rightNumber == 0)
    		result.add(s.toString());
    	else if (leftNumber > 0) {
    		s.append('(');
    		leftNumber--;
    		DFS(leftNumber, rightNumber, s, result);
    		s.deleteCharAt(s.length() - 1);
    		leftNumber++;
    	}
    	if (rightNumber > 0 && rightNumber > leftNumber) {//
    		s.append(')');
    		rightNumber--;
    		DFS(leftNumber, rightNumber, s, result);
    		s.deleteCharAt(s.length() - 1);
    		rightNumber++;
    	}
    }
    
    public static List<String> generateParenthesis(int n) {
    	if (n <= 0)
    		return new ArrayList<String>();
    	List<String> result = new ArrayList<String>();
    	StringBuffer s = new StringBuffer();
    	DFS(n, n, s, result);
    	return result;
    }

Log in to reply
 

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