Leetcode 22. Generate Parentheses
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
n
?
n
can range from 1 to 8 or 10 for competitive programming problems due to the exponential growth in the number of combinations.To solve this problem, a common approach is to use backtracking. The idea is to build the parentheses string step by step and ensure that at every step the string being built is a valid prefix of some valid well-formed parentheses combination.
2 * n
, add the string to the result list.n
).#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generateParenthesisRecursive(result, "", 0, 0, n);
return result;
}
private:
void generateParenthesisRecursive(vector<string>& result, string current, int open, int close, int n) {
if(current.size() == n * 2) {
result.push_back(current);
return;
}
// Try adding an open parenthesis if we can
if(open < n) {
generateParenthesisRecursive(result, current + "(", open + 1, close, n);
}
// Try adding a close parenthesis if we can
if(close < open) {
generateParenthesisRecursive(result, current + ")", open, close + 1, n);
}
}
};
// Example usage:
int main() {
Solution solution;
int n = 3;
vector<string> result = solution.generateParenthesis(n);
for(const string& combination : result) {
cout << combination << endl;
}
return 0;
}
The time complexity of this approach is O(4^n / sqrt(n))
. This is derived from the fact that the number of valid permutations of n
pairs of parentheses is the Catalan number, which is C(n) = (1 / (n + 1)) * (2n choose n)
.
Thus, the number of function calls grows exponentially with n
, explaining the exponential nature of 4^n
. The division by sqrt(n)
comes from the combinatorial reduction factor related to Catalan numbers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?