-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path22.括号生成.cpp
43 lines (36 loc) · 926 Bytes
/
22.括号生成.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
/*
* @lc app=leetcode.cn id=22 lang=cpp
*
* [22] 括号生成
*/
// @lc code=start
class Solution
{
public:
void generate(std::vector<std::string> &result, int index, int n, std::string &steps, int leftused, int rightused)
{
if (leftused > n || rightused > leftused)
{
return;
}
if (rightused == n)
{
result.push_back(steps);
return;
}
steps[index] = '(';
generate(result, index + 1, n, steps, leftused + 1, rightused);
steps[index] = ')';
generate(result, index + 1, n, steps, leftused, rightused + 1);
}
vector<string> generateParenthesis(int n)
{
std::vector<std::string> result;
std::string steps(2 * n, '.');
steps[0] = '(';
steps[2 * n - 1] = ')';
generate(result, 1, n, steps, 1, 0);
return result;
}
};
// @lc code=end