Skip to content

Commit 22037de

Browse files
committed
generate_parentheses.cpp
1 parent 2e86fd3 commit 22037de

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

generate_parentheses.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
vector<string> generateParenthesis(int n) {
4+
vector<string> result;
5+
core(n, n, n, string(), result);
6+
return result;
7+
}
8+
9+
void core(int n, int left, int right, string str, vector<string>& result)
10+
{
11+
if (left == 0)
12+
{
13+
str.append(right, ')');
14+
result.push_back(str);
15+
return;
16+
}
17+
18+
if (left == n)
19+
{
20+
core(n, left - 1, right, str + '(', result);
21+
return;
22+
}
23+
24+
if (right >= left)
25+
{
26+
core(n, left - 1, right, str + '(', result);
27+
}
28+
29+
if (n - right < n - left)
30+
{
31+
core(n, left, right - 1, str + ')', result);
32+
}
33+
}
34+
};

0 commit comments

Comments
 (0)