Generate Parenthesis
Problem Statement:β
GivenΒ nΒ pairs of parentheses, write a function toΒ generate all combinations of well-formed parentheses.
-
Example:
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
β Solution: Backtrackingβ
class Solution {
public:
// Recursive function to generate all valid parentheses combinations
void genP(int n, int open, int close, string ¤t, vector<string> &result){
if(open == n && close == n){
result.push_back(current); // Found valid combination
return;
}
if(open < n) {
current.push_back('('); // Add opening bracket
genP(n, open + 1, close, current, result);
current.pop_back(); // Backtrack
}
if(close < open) {
current.push_back(')'); // Add closing bracket
genP(n, open, close + 1, current, result);
current.pop_back(); // Backtrack
}
}
vector<string> generateParentheses(int n) {
vector<string> result;
string current = "";
genP(n, 0, 0, current, result);
return result;
}
};
π How It Worksβ
- The goal is to generate all combinations of n pairs of valid parentheses.
- We maintain:
open: number of'('used so farclose: number of')'used so far- A string
currentthat builds the current sequence
- If both
openandclosereachn, weβve built a valid sequence. - The function backtracks by removing the last character after recursive calls.
π§© Key Logicβ
- You can only add
'('ifopen < n - You can only add
')'ifclose < opento maintain valid pairing.
β±οΈ Time & Space Complexityβ
| Aspect | Value |
|---|---|
| Time Complexity | O(2βΏ) β More precisely: O(Catalan(n)) |
| Space Complexity | O(n) stack depth per call, O(Catalan(n)) result size |
For n = 3, the valid combinations are 5 β This is the Catalan number: Cβ = (2n)! / ((n+1)! * n!)
β οΈ Edge Casesβ
- n = 0 β return empty list
- n = 1 β return ["()"]
π‘ Other Approachesβ
- Brute force: Generate all 2^(2n) sequences and filter β β very inefficient
- BFS with queue (alternative to DFS recursion)
π Related Problemsβ
π¬