File tree Expand file tree Collapse file tree 2 files changed +44
-1
lines changed
Expand file tree Collapse file tree 2 files changed +44
-1
lines changed Original file line number Diff line number Diff 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 ) |
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments