- Link: 22. Generate Parentheses - Medium
- Track: NeetCode150 Amazon
Question
- Example 1:
- Input: n = 3
- Output:
["((()))","(()())","(())()","()(())","()()()"]
Restate
- Given
npairs of parentheses, generate all valid combinations. - A string is valid if at any prefix,
)never exceeds(, and total length is2n.
Edge Case
n = 1→["()"]n = 0→[""]
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Backtracking |
Method 1 - Backtracking
Key idea:
During backtracking, never let)exceed(
with remaining counts, you can add)only whenright > left
回溯时始终保证任意前缀里 右括号数量不超过左括号;用剩余计数表示就是:只有当right > left(剩余右括号多于剩余左括号)时才能加)`。要列举全部解(combinations) + 每步只有少量选择 + 可以提前判非法 → backtracking
Approach
- Build the parentheses string one character at a time.
- Track how many parentheses are remaining:
left: remaining'('right: remaining')'
- Choices at each step:
- Add
'('ifleft > 0 - Add
')'only ifright > left(so we never close more than we’ve opened)
- Add
- When
left == 0andright == 0, we formed a valid string → append to result.
Complexity
- Time Complexity:
- :第 n 个 Catalan number,一共有多少个合法括号字符串(答案数量)。
- n:每个答案的长度是
2n,生成一个字符串需要 时间 - is a loose upper bound, but backtracking prunes(剪枝) invalid
- Space Complexity:
Code
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def dfs(path, left, right):
if left == 0 and right == 0:
res.append("".join(path))
return
if left > 0:
path.append("(")
dfs(path, left - 1, right)
path.pop()
if right > 0 and left < right:
path.append(")")
dfs(path, left, right - 1)
path.pop()
dfs([], n, n)
return resMistake
- add
)only when you have already placed more(than)so far