-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path022.cpp
33 lines (32 loc) · 880 Bytes
/
022.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
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
backtracking(res, n, 0, 0, "");
return res;
}
// 回溯法实现
void backtracking(vector<string> &res, int num, int index, int leftindex, string local)
{
// 退出条件
if(2*num == index)
{
res.push_back(local);
return;
}
// 左括号个数小于给定值
if(leftindex < num)
{
local.push_back('(');
backtracking(res, num, index+1, leftindex+1, local);
local.pop_back();
}
// 右括号个数小于左括号个数
if(index-leftindex < leftindex)
{
local.push_back(')');
backtracking(res, num, index+1, leftindex, local);
local.pop_back();
}
}
};