Skip to content

Generate Parentheses

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

nOutputCount
1["()"]1
2["(())","()()"]2
3["((()))","(()())","(())()","()((})","()()()"]5
  • 1 <= n <= 8
  • The number of well-formed strings grows as the nth Catalan number: C(n) = (2n)! / ((n+1)! * n!)
ApproachTimeSpaceNotes
BacktrackingO(4^n / √n)O(n)Prunes invalid paths early; intuitive recursion
Dynamic ProgrammingO(4^n / √n)O(n)Builds bottom-up; combines subproblems

Both approaches have the same asymptotic complexity (Catalan number), but backtracking prunes earlier.

★ Recommended

Use backtracking to generate parentheses recursively. At each step, decide whether to add an opening or closing parenthesis:

  • Add ( if we have fewer than n opening parentheses.
  • Add ) if we have fewer closing than opening parentheses (maintains validity).

This prunes invalid paths immediately, making it more efficient than brute force.

⏱ Time O(4^n / √n) Catalan number growth 💾 Space O(n) Recursion depth + result

Input: n = 2

Start: ""
├─ Add '(': "("
│ ├─ Add '(': "(("
│ │ └─ Add ')': "(()"
│ │ └─ Add ')': "(())" ✓
│ └─ Add ')': "()"
│ └─ Add '(': "()("
│ └─ Add ')': "()()" ✓
└─ Can't add ')' yet (left == 0)
Result: ["(())", "()()"]
function generateParenthesis(n):
result = []
def backtrack(current, leftCount, rightCount):
if len(current) == 2 * n:
result.append(current)
return
if leftCount < n:
backtrack(current + "(", leftCount + 1, rightCount)
if rightCount < leftCount:
backtrack(current + ")", leftCount, rightCount + 1)
backtrack("", 0, 0)
return result
generate_parentheses_backtracking.py
from typing import List
def generateParenthesis(n: int) -> List[str]:
"""Backtracking approach: O(4^n) time, O(n) space"""
result = []
def backtrack(current, left, right):
if len(current) == 2 * n:
result.append(current)
return
if left < n:
backtrack(current + "(", left + 1, right)
if right < left:
backtrack(current + ")", left, right + 1)
backtrack("", 0, 0)
return result
✓ Simple

Build valid parentheses combinations bottom-up. For i pairs, insert all valid combinations of j pairs inside parentheses, then append all valid combinations of remaining (i-1-j) pairs.

The recurrence: DP[i] = "(" + DP[j] + ")" + DP[i-1-j] for all valid j.

⏱ Time O(4^n / √n) Catalan number 💾 Space O(n) DP table + recursion

Input: n = 2

DP[0] = [""]
DP[1] = ["()"] (from: "(" + DP[0] + ")" + DP[0])
DP[2] = [
"(" + "()" + ")" + "" = "(())",
"(" + "" + ")" + "()" = "()()"
]
function generateParenthesis(n):
dp = [[] for _ in range(n + 1)]
dp[0] = [""]
for i in range(1, n + 1):
for j in range(i):
for left in dp[j]:
for right in dp[i - 1 - j]:
dp[i].append("(" + left + ")" + right)
return dp[n]
generate_parentheses_dp.py
from typing import List
def generateParenthesis(n: int) -> List[str]:
"""DP approach: O(4^n) time, O(n) space"""
if n == 0:
return [""]
dp = [[] for _ in range(n + 1)]
dp[0] = [""]
for i in range(1, n + 1):
for j in range(i):
for left in dp[j]:
for right in dp[i - 1 - j]:
dp[i].append("(" + left + ")" + right)
return dp[n]