-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_parentheses.cpp
More file actions
55 lines (52 loc) · 1.26 KB
/
generate_parentheses.cpp
File metadata and controls
55 lines (52 loc) · 1.26 KB
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
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Describe: Given n pairs of parentheses, write a function to generate all
* combinations of well-formed parentheses.
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> rst;
if (n <= 0) {
return rst;
}
string cur;
recusive(rst, cur, 0, 0, n);
return rst;
}
void recusive(vector<string> &rst, string cur, int forward, int backward,
int len) {
// indicate all element is added
if (backward == len) {
rst.push_back(cur);
return;
}
string str = cur;
for (int i = forward + 1; i <= len; ++i) {
cur.push_back('(');
str = cur;
for (int j = backward + 1; j <= i; ++j) {
str.push_back(')');
recusive(rst, str, i, j, len);
}
}
}
};
int main() {
Solution so;
string str;
vector<int> test;
int n;
while (cin >> n) {
auto re = so.generateParenthesis(n);
cout << "result: " << endl;
for (auto &ele : re) {
cout << ele << endl;
}
}
return 0;
}