-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.generate-parentheses.cpp
More file actions
45 lines (44 loc) · 925 Bytes
/
22.generate-parentheses.cpp
File metadata and controls
45 lines (44 loc) · 925 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
/*
* @lc app=leetcode id=22 lang=cpp
*
* [22] Generate Parentheses
*/
#include <vector>
#include <string>
using namespace std;
// @lc code=start
class Solution
{
public:
vector<string> generateParenthesis(int n)
{
vector<string> res;
vector<char> buf;
gen(n, 0, buf, res);
return res;
}
void gen(int rcnt, int ecnt, vector<char> &buf, vector<string> &res)
{
if (rcnt == 0 && ecnt == 0)
{
res.push_back(string(buf.begin(), buf.end()));
return;
}
// eject first
if (rcnt > 0)
{
buf.push_back('(');
gen(rcnt - 1, ecnt + 1, buf, res);
buf.pop_back();
}
// close
if (ecnt > 0)
{
buf.push_back(')');
gen(rcnt, ecnt - 1, buf, res);
buf.pop_back();
}
return;
}
};
// @lc code=end