-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22. Generate Parantheses.cpp
55 lines (42 loc) · 1.12 KB
/
22. Generate Parantheses.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
class Solution {
void helper(int n, string result, int left, int right, vector<string> &ans) {
//cout << result << endl;
if (left == n && right == n) {
ans.push_back(result);
return;
}
if (left < n)
helper(n, result + "(", left+1, right, ans);
if(left > right)
helper(n, result + ")", left, right+1, ans);
}
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
if(!n) {
ans.push_back("");
return ans;
}
helper(n, "", 0, 0, ans);
return ans;
}
};
---------
class Solution {
public:
void genpar(int left, int right, vector<string> &result, const string &cur) {
if(!left && !right) {
result.push_back(cur);
return;
}
if(left > 0)
genpar(left-1,right,result,cur+'(');
if (right > left)
genpar(left,right-1,result,cur+')');
}
vector<string> generateParenthesis(int n) {
vector<string> result;
genpar(n,n,result,"");
return result;
}
};