-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.GenerateParentheses.cpp
More file actions
36 lines (36 loc) · 924 Bytes
/
22.GenerateParentheses.cpp
File metadata and controls
36 lines (36 loc) · 924 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
class Solution {
public:
vector<string> generateParenthesis(int n) {
if(n <= 0){
return vector<string>();
}
vector<string> res;
string t = "";
generateParenthesis(res, t, n);
return res;
}
void generateParenthesis(vector<string>& res, string& t, int n){
if(t.size() == 2*n){
//std::cout << t << std::endl;
if(valid(t))
res.push_back(t);
}
else{
t.push_back('(');
generateParenthesis(res, t, n);
t.pop_back();
t.push_back(')');
generateParenthesis(res, t, n);
t.pop_back();
}
}
bool valid(string& t){
int bal = 0;
for(int i = 0; i < t.size(); i++){
t[i] == '(' ? bal++ : bal--;
if(bal<0)
return false;
}
return bal == 0;
}
};