Skip to content

Commit daf4344

Browse files
committed
"Generate Parentheses"
1 parent d75b721 commit daf4344

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
269269
| 25 | [Reverse Nodes in k-Group] | |
270270
| 24 | [Swap Nodes in Pairs] | |
271271
| 23 | [Merge k Sorted Lists] | |
272-
| 22 | [Generate Parentheses] | |
272+
| 22 | [Generate Parentheses] | [C++](src/21.cpp) |
273273
| 21 | [Merge Two Sorted Lists] | [C](src/21.c) |
274274
| 20 | [Valid Parentheses] | [C](src/20.c) |
275275
| 19 | [Remove Nth Node From End of List] | [C](src/19.c) |

src/22.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <vector>
4+
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<string> generateParenthesis(int n) {
10+
vector<string> ans;
11+
string temp = "";
12+
13+
generateParenthesisHelper(ans, temp, n, n);
14+
15+
return ans;
16+
}
17+
18+
void generateParenthesisHelper(vector<string> &ans, string temp, int left, int right) {
19+
if (left > right) return;
20+
21+
if (left == 0 && right == 0) {
22+
ans.push_back(temp);
23+
return;
24+
}
25+
26+
if (left > 0)
27+
generateParenthesisHelper(ans, temp + "(", left - 1, right);
28+
if (right > 0)
29+
generateParenthesisHelper(ans, temp + ")", left, right - 1);
30+
}
31+
};
32+
33+
int main() {
34+
int n = 4;
35+
Solution s;
36+
vector<string> ans = s.generateParenthesis(n);
37+
38+
for (int i = 0; i < ans.size(); i++) {
39+
cout << ans[i] << endl;
40+
}
41+
42+
return 0;
43+
}

0 commit comments

Comments
 (0)