-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerateParenthesis.cpp
More file actions
52 lines (45 loc) · 837 Bytes
/
generateParenthesis.cpp
File metadata and controls
52 lines (45 loc) · 837 Bytes
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
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> combinations;
string init;
for (int i = 0; i < 2*n; i++) {
string s(1, '('), s2(1, ')');
if (i < n) {
init += s;
} else {
init += s2;
}
}
do {
if (Solution::is_valid(init)) {
combinations.push_back(init);
}
} while (next_permutation(init.begin(), init.end()));
return combinations;
}
bool is_valid(string input) {
int sum = 0;
for (auto c : input) {
if (c == '(') sum++;
else if (c== ')') sum--;
if (sum < 0) {
return false;
}
}
return sum == 0 ? true : false;
}
};
int main()
{
Solution s;
auto v = s.generateParenthesis(5);
for (auto s : v) {
printf("%s \n", s.c_str());
}
return 0;
}