-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.cpp
63 lines (59 loc) · 1.25 KB
/
GenerateParentheses.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/***
* DFS
* '(' ')'的递归深度分别为n
* 当两者都达到n时,输出
* 递归过程中要保证'('个数不少于')'
***/
/*
class Solution {
public:
vector<string> generateParenthesis(int n) {
string s;
dfs(n, n, s);
return vpares;
}
private:
vector<string> vpares;
void dfs(int left, int right, string s)
{
if ((0 == left) && (0 == right))
{
vpares.push_back(s);
return;
}
if (left > 0)
dfs(left-1, right, s + "(");
if (right > left) // caution!!!
dfs(left, right-1, s + ")");
return;
}
};
*/
/***
* 法2:DFS,同法1
* 优化,当left深度达到n时,right不用再递归处理了,直接补全剩余的')'
***/
class Solution {
public:
vector<string> generateParenthesis(int n) {
string s;
dfs(n, n, s);
return vpares;
}
private:
vector<string> vpares;
void dfs(int left, int right, string s)
{
if (0 == left)
{
s.append(right, ')'); // add left ')'
vpares.push_back(s);
return;
}
if (left > 0)
dfs(left-1, right, s + '(');
if (right > left)
dfs(left, right-1, s + ')');
return;
}
};