1. Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
2. Example
Example 1
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 1
Output: ["()"]
3. Constraints
4. Solutions
Backtracking
Time complexity: O($\frac {4^n} {\sqrt{n}}$)
Space complexity: O($\frac {4^n} {\sqrt{n}}$)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| class Solution {
public:
vector<string> generateParenthesis(int n) {
string parenthesis;
parenthesis.reserve(2 * n);
vector<string> results;
generate_parenthesis(parenthesis, n, n, results);
return results;
}
private:
void generate_parenthesis(string &parenthesis, int left, int right, vector<string> &results) {
if (left == 0 && right == 0) {
results.push_back(parenthesis);
} else {
if (left > 0) {
parenthesis.push_back('(');
generate_parenthesis(parenthesis, left - 1, right, results);
parenthesis.pop_back();
}
if (right > left) {
parenthesis.push_back(')');
generate_parenthesis(parenthesis, left, right - 1, results);
parenthesis.pop_back();
}
}
}
};
|