-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22_Generate_Parentheses_180725.cpp
50 lines (46 loc) · 1.33 KB
/
22_Generate_Parentheses_180725.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
class Solution {
public:
void parentheses(vector<vector<int>> &res, vector<int> &tempRes, int &n);
vector<string> generateParenthesis(int n) {
vector<vector<int>> res;
vector<int> tempRes(2*n,0);
parentheses(res, tempRes, n);
string tempStr;
vector<string> resStr;
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++){
if(res[i][j]==-1) tempStr.push_back('(');
if(res[i][j]==1) tempStr.push_back(')');
}
resStr.push_back(tempStr);
}
return resStr;
}
};
//-1 is (, +1 is )
void parentheses(vector<vector<int>> &res, vector<int> &tempRes, int &n){
if(2*n==tempRes.size()){
res.push_back(tempRes);
return;
}
int balance;
for(auto i:tempRes)
balance+=i;
if(balance>=0){ //need more "("
tempRes.push_back(-1);
parentheses(res,tempRes,n);
tempRes.pop_back();
}
if(balance<=0){ //need more ")"
tempRes.push_back(1);
parentheses(res,tempRes,n);
tempRes.pop_back();
}
}
bool compareVec(vector<int> a, vector<int> b){
if(a.size()!=b.size()) return false;
for(int i=0;i<a.size();i++){
if(a[i]!=b[i]) return false;
}
return true;
}