Backtracking
Medium
Generate Parentheses
Generate all combinations of well-formed parentheses.
10 min read
Solve on LeetCodeProblem Understanding
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Algorithm Strategy
Instead of generating all $2^{2n}$ strings and validating them, we can build only valid strings.
Rules:
- Open: We can add an open parenthesis
(ifopen_count < n. - Close: We can add a closing parenthesis
)ifclosed_count < open_count.
This ensures we never close more than we open (validity) and never exceed n (completeness).
Interactive Visualization
Step 1 / 1
Empty Heap
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
