-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode22_generate_parentheses.cpp
68 lines (58 loc) · 1.42 KB
/
leetcode22_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* @file leetcode22_generate_parentheses.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2022/08/14 11:30:13
* @brief https://leetcode.com/problems/generate-parentheses/
*
**/
#include <iostream>
#include <string>
#include <vector>
class Solution {
public:
std::vector<std::string> generateParenthesis(int n) {
std::string s;
std::vector<std::string> result_vec;
helper(n, 0, 0, s, result_vec);
return result_vec;
}
private:
void helper(
int n,
int left,
int right,
std::string& s,
std::vector<std::string>& result_vec) {
if (left == n && right == n) {
result_vec.push_back(s);
return;
}
// Put a '('
if (left < n) {
s.push_back('(');
helper(n, left+1, right, s, result_vec);
s.pop_back();
}
if (right < left) {
s.push_back(')');
helper(n, left, right+1, s, result_vec);
s.pop_back();
}
return;
}
};
int main() {
while (1) {
std::cout << "Input integer (control-C to exit): ";
int x = 0;
if (!(std::cin >> x)) {
return 0;
}
Solution solution;
auto ret = solution.generateParenthesis(x);
for (auto s: ret) {
std::cout << s << std::endl;
}
}
return 0;
}