-
Notifications
You must be signed in to change notification settings - Fork 95
/
generate-parenthese.cpp
45 lines (45 loc) · 1.31 KB
/
generate-parenthese.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
class Solution {
public:
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> instack;
vector<int> lpleft;
vector<string> res;
res.push_back(""); instack.push_back(0); lpleft.push_back(n);
for(int i = 1; i <= 2 * n; i++)
{
int sz = res.size();
bool canadd;
for(int j = 0; j < sz; j++)
{
if(lpleft[j]>0 && instack[j]>0)
canadd = true;
else
canadd = false;
if(lpleft[j] > 0)
{
if(canadd)
{
res.push_back(res[j]+"(");
instack.push_back(instack[j]+1);
lpleft.push_back(lpleft[j]-1);
}
else
{
res[j] += "(";
instack[j]++;
lpleft[j]--;
continue;
}
}
if(instack[j]>0)
{
res[j] += ")";
instack[j]--;
}
}
}
return res;
}
};