-
Notifications
You must be signed in to change notification settings - Fork 0
/
0022.generate_parentheses.cpp
54 lines (44 loc) · 1.02 KB
/
0022.generate_parentheses.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
51
52
53
54
#include <iostream>
#include <vector>
#include <string>
using std::vector, std::string;
vector<string> generate_parenthesis(int n)
{
vector<string> res;
string path;
n *= 2;
auto backtracking = [&res, &path, n](auto&& self, int k, int c) {
if (c < 0) return ;
if (path.size() == n && c == 0) {
res.push_back(path);
return ;
}
for (int i = k; i < n; ++i) {
++c;
path.push_back('(');
self(self, i + 1, c);
path.pop_back();
--c;
--c;
path.push_back(')');
self(self, i + 1, c);
path.pop_back();
++c;
}
};
backtracking(backtracking, 0, 0);
return res;
}
int main () {
#ifdef LOCAL
freopen("0022.in", "r", stdin);
#endif
int n = 0;
while (std::cin >> n) {
vector<string> res = generate_parenthesis(n);
for (const auto& e : res) {
std::cout << e << std::endl;
}
}
return 0;
}