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
|
class Solution {
public:
vector<string> ans;
void genStep(string &item,int n,int countLeft,int countRight)
{
if(countLeft == n && countRight == n)
{
ans.push_back(item);
return;
}
if(countLeft < n)
{
countLeft++;
item.insert(item.length(),"(");
genStep(item,n,countLeft,countRight);
countLeft--;
item = item.erase(item.length()-1,1);
}
if(countRight < n && countLeft > countRight)
{
countRight++;
item.insert(item.length(),")");
genStep(item,n,countLeft,countRight);
countRight--;
item = item.erase(item.length()-1,1);
}
}
vector<string> generateParenthesis(int n) {
ans.clear();
if(n == 0)return ans;
int countLeft = 1;
int countRight = 0;
string item = "(";
genStep(item,n,countLeft,countRight);
return ans;
}
};
|