sagelearnai

Generate Parentheses

Difficulty: Medium · Pattern: Backtracking · LeetCode #22

Return every string of n pairs of parentheses that is well-formed (balanced and properly nested), in any order.

Examples

text
n = 3  →  ["((()))", "(()())", "(())()", "()(())", "()()()"]
n = 1  →  ["()"]

Hints

  1. Generating all 2^(2n) strings and filtering works but is wasteful.
  2. You may add ( as long as you've used fewer than n of them.
  3. You may add ) only if it closes something, i.e. closes < opens.

Approach

Backtrack while tracking opened and closed counts. Add ( if opened < n; add ) if closed < opened. When the string has length 2n, it's guaranteed valid, so record it. These two rules prune every invalid prefix, so we only ever build valid strings. The count is the n-th Catalan number.

Complexity

Time: O(4ⁿ/√n), the Catalan number times string length. Space: O(n) recursion.

Python solution
def generateParenthesis(n):
    res = []
    def bt(s, opened, closed):
        if len(s) == 2 * n:
            res.append(s)
            return
        if opened < n:
            bt(s + "(", opened + 1, closed)
        if closed < opened:
            bt(s + ")", opened, closed + 1)
    bt("", 0, 0)
    return res
JavaScript solution
function generateParenthesis(n) {
  const res = [];
  const bt = (s, opened, closed) => {
    if (s.length === 2 * n) { res.push(s); return; }
    if (opened < n) bt(s + '(', opened + 1, closed);
    if (closed < opened) bt(s + ')', opened, closed + 1);
  };
  bt('', 0, 0);
  return res;
}