22. 括号生成
为保证权益,题目请参考 22. 括号生成(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
class Solution
{
public:
vector<string> ans;
vector<string> generateParenthesis(int n)
{
gen(n, 0, "");
return ans;
}
void gen(int last_l, int last_r, string tmp)
{
if (last_l > 0)
{
gen(last_l - 1, last_r + 1, tmp + "(");
if (last_r > 0)
{
gen(last_l, last_r - 1, tmp + ")");
}
}
else if (last_r > 0)
{
gen(last_l, last_r - 1, tmp + ")");
}
else
{
ans.push_back(tmp);
}
}
};
int main()
{
return 0;
}
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
31
32
33
34
35
36
37
38
39
40
41
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
31
32
33
34
35
36
37
38
39
40
41