[LeetCode] Generate Parentheses

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

DFS

Time Complexity
O(2^n)
It is traverse of a tree.
The level is 2n.
O(2^2n - 1) --> O(2^n)
Space Complexity
O(N)

思路

We can think it as a tree. The depth of the tree is the length of the parentheses. The base case if left + right = 2*n. The recursion rule is add "(" or ")". A valid parentheses should following left parentheses should less than n and the right parentheses should less or equal to left parentheses.

代码

public List generateParenthesis(int n) {
    List res = new ArrayList();
    if(n == 0) return res;
    StringBuilder sb = new StringBuilder();
    dfs(res, sb, n, 0, 0);
    return res;
}

private void dfs(List res, StringBuilder sb, int n, int left, int right){
    if(left == n && right == n) res.add(sb.toString()); return;
    
    //add left
    if(left < n){
        sb.append("(");
        dfs(res, sb, n, left + 1, right);
        sb.deleteCharAt(sb.length() - 1);
    }
    
    //add right
    if(right < left){
        sb.append(")");
        dfs(res, sb, n, left, right + 1);
        sb.deleteCharAt(sb.length() - 1);
    }
}

你可能感兴趣的:(leetcode,LintCode)