Generate Parentheses

Medium

Topics
StringBacktrackingDynamic Programming

Given n pairs of parentheses, return all combinations of well-formed parentheses, in any order.

Example 1

((()))(()())(())()()(())()()()
Every well-formed string of 3 pairs. The two rules that generate exactly these and nothing else: open a bracket while fewer than 3 are open, and close one only while closes trail opens. That prunes invalid prefixes instead of filtering at the end. There are 5.
Each chip is one valid output string.
Input:  n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2

()
Input:  n = 1
Output: ["()"]

Constraints

  • 1 <= n <= 8
Editorial — intuition, approach, complexity and pitfalls

Intuition

Build the string one character at a time. You may add "(" while you still have opens left, and ")" only while it would not exceed the number of opens placed — this guarantees validity by construction.

Approach

  1. DFS carrying counts of open and close brackets used.
  2. Add "(" if open < n; add ")" if close < open.
  3. When the string reaches length 2n it is a valid answer.

Dry Run

n = 3. Two counters, and the only two rules are "never open more than n" and
"never close more than you have opened".
  ""        op 0 cl 0   may open
    "("       op 1 cl 0   may open, may close
      "(("      op 2 cl 0   may open, may close
        "((("     op 3 cl 0   open is exhausted, may only close
          "((()"  -> "((())" -> "((()))"   complete
        "(()"     op 2 cl 1   may open, may close
          "(()(" -> "(()()" -> "(()())"    complete
          "(())" -> "(())(" -> "(())()"    complete
      "()"      op 1 cl 1   may open
        "()(" -> "()((" -> "()(()" -> "()(())"   complete
        "()()" -> "()()(" -> "()()()"            complete
answer ((())) | (()()) | (())() | ()(()) | ()()()
No validity check is ever run on a finished string, and that is the point. The two
guards make it impossible to construct an invalid prefix, so every leaf at length
2n is valid by construction -- which is why this generates the 5 Catalan strings
rather than filtering 2^6 = 64 candidates.
The close guard is `cl < op`, not `cl < n`. Those differ the moment a string has
more closes than opens so far. Using `cl < n` for n = 2 produces
(()) ()() ())( )(() )()( ))((  -- six strings, of which only the first two are
balanced.

Complexity

  • Time — O(4^n / sqrt(n)): the count of valid strings is the nth Catalan number.
  • Space — O(n): recursion depth.

Common Pitfalls

  • Only close when close < open, or you produce invalid strings like ")(".

Full Solution — all languages

class Solution:
    def generateParenthesis(self, n):
        res=[]
        def dfs(cur,op,cl):
            if len(cur)==2*n: res.append(cur); return
            if op<n: dfs(cur+'(',op+1,cl)
            if cl<op: dfs(cur+')',op,cl+1)
        dfs('',0,0)
        return res
SensAI
Beta
Tap the mic to stop voice mode