BacktrackingAnimated
Generate Parentheses
Add "(" while fewer than n are used, and ")" while it would stay balanced.
Time
O(4ⁿ / √n)
Extra space
O(n)
Use it for
All valid bracket strings.
How it works
- Build the string one character at a time.
- You may add "(" while fewer than n have been used.
- You may add ")" only while there are more "(" than ")" so far. This rule is the pruning: it never lets the string become invalid.
- When the string has length 2n, record it. Backtrack to explore the other choices. The count is the Catalan number.
Watch it run
Loading animation…