22 Generate Parentheses

1. Question

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

2. Implementation

(1) Backtracking

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        StringBuilder paren = new StringBuilder();
        getParenthesis(0, 0, n, paren, res);
        return res;
    }

    public void getParenthesis(int left, int right, int n, StringBuilder paren, List<String> res) {
        if (paren.length() == 2 * n) {
            res.add(paren.toString());
            return;
        }

        if (left < n) {
            paren.append('(');
            getParenthesis(left + 1, right, n, paren, res);
            paren.setLength(paren.length() - 1);
        }

        if (right < left) {
            paren.append(')');
            getParenthesis(left, right + 1, n, paren, res);
            paren.setLength(paren.length() - 1);
        }
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)

Last updated