0%

22.Generate Parentheses

框架

1
2
3
4
5
6
class Solution {
public:
vector<string> generateParenthesis(int n) {

}
};

1. 递归

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:
void recursion(string s, int total, int cur) {
if (total == n) {
while (cur > 0) {
s += ')';
cur--;
}
vec.push_back(s);
return;
}

recursion(vec, s + '(', total + 1, cur + 1, n);
if (cur > 0)
recursion(vec, s + ')', total, cur - 1, n);
}

vector<string> generateParenthesis(int n) {
vec.clear();
this->n = n;

recursion(ans, "(", 1, 1);

return ans;
}

private:
vector<string> vec;
int n;
};