-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_parenthesis.cpp
More file actions
41 lines (37 loc) · 898 Bytes
/
Copy pathgenerate_parenthesis.cpp
File metadata and controls
41 lines (37 loc) · 898 Bytes
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
/*
22. Generate Parentheses
Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
if(n==0)
return result;
helper("",n, n, n, result);
return result;
}
void helper(string s, int left, int right, int n, vector<string>& result){
// if(left==0 && right==0)
// return ;
if(s.length()==2*n){
result.push_back(s);
return;
}
if(left>0){
helper(s+"(", left-1, right, n, result);
}
if(left<right && right>0){
helper(s+")", left, right-1, n, result);
}
}
};