Algorithm Day60 - Generate Parentheses (lc-22)
🧩 Problem Description
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
💬 Example
1 | Input: n = 3 |
1 | Input: n = 1 |
💡 Approach: Backtracking
We need to ensure:
- We never place
')'
unless there is a matching'('
available. - The number of
'('
used cannot exceedn
. - The number of
')'
cannot exceed the number of'('
at any point.
So the recursive function tracks:
open
: how many'('
have been used.close
: how many')'
have been used.
Valid recursion continues while open <= n
and close <= open
.
🔢 Java Code
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(4^n / √n), which is the Catalan number count.
- Space: O(n) recursion depth + output size.
✍️ Summary
- Classic backtracking problem generating balanced parentheses.
- Use counts of
open
andclose
to ensure validity. - Total solutions = nth Catalan number.
Related problems:
lc-301
— Remove Invalid Parentheseslc-856
— Score of Parentheseslc-678
— Valid Parenthesis String