-
Notifications
You must be signed in to change notification settings - Fork 118
/
22.cpp
43 lines (33 loc) · 955 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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string temp = "";
generateParenthesisHelper(ans, temp, n, n);
return ans;
}
void generateParenthesisHelper(vector<string> &ans, string temp, int left, int right) {
if (left > right) return;
if (left == 0 && right == 0) {
ans.push_back(temp);
return;
}
if (left > 0)
generateParenthesisHelper(ans, temp + "(", left - 1, right);
if (right > 0)
generateParenthesisHelper(ans, temp + ")", left, right - 1);
}
};
int main() {
int n = 4;
Solution s;
vector<string> ans = s.generateParenthesis(n);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
return 0;
}