Generate Parentheses - Problem
Imagine you're designing a bracket balancer that needs to generate all possible valid combinations of parentheses for mathematical expressions. Given n pairs of parentheses, your task is to write a function that generates all combinations of well-formed parentheses.
A well-formed parentheses string means:
- Every opening parenthesis
(has a corresponding closing parenthesis) - Parentheses are properly nested (no closing before opening)
- The string is balanced (equal number of opening and closing)
Example: For n = 3, valid combinations include "((()))", "(()())", "(())()", "()(())", "()()()"
This problem tests your ability to generate all valid sequences while avoiding invalid ones - a perfect application of backtracking with constraint validation!
Input & Output
example_1.py — Basic Case
$
Input:
n = 3
›
Output:
["((()))","(()())","(())()","()(())","()()()"]
💡 Note:
For n=3, we need 3 pairs of parentheses. All 5 possible well-formed combinations are shown, each using exactly 3 opening and 3 closing parentheses in valid order.
example_2.py — Small Case
$
Input:
n = 1
›
Output:
["()"]
💡 Note:
With only 1 pair of parentheses, there's exactly one valid combination: one opening followed by one closing parenthesis.
example_3.py — Two Pairs
$
Input:
n = 2
›
Output:
["(())","()()"]
💡 Note:
For n=2, there are exactly 2 valid combinations: nested parentheses "(())" and sequential parentheses "()()".
Constraints
- 1 ≤ n ≤ 8
- The number of valid combinations follows the Catalan numbers: C(n) = (2n)! / ((n+1)! × n!)
- Result size will be at most 1430 combinations (when n=8)
Visualization
Tap to expand
Understanding the Visualization
1
Start Empty
Begin with empty string and zero counts
2
Smart Decisions
At each node, add '(' if open < n, add ')' if close < open
3
Valid Paths Only
Never explore invalid combinations
4
Collect Results
When length = 2n, we have a valid combination
Key Takeaway
🎯 Key Insight: Use backtracking with smart constraints (open < n, close < open) to generate only valid parentheses combinations, achieving optimal Catalan number complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code