Leetcode 22. Generate Parentheses

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Generate Parentheses

2. Solution

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
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
push(0, 0, result, "", n, '(');
return result;
}

private:
void push(int left, int right, vector<string>& result, string s, const int n, char ch) {
s += ch;
if(ch == '(') {
left++;
}
else {
right++;
}
if(left > n || right > n || right > left) {
return;
}
if(s.length() == 2 * n) {
result.push_back(s);
return;
}
push(left, right, result, s, n, '(');
push(left, right, result, s, n, ')');
}
};

Reference

  1. https://leetcode.com/problems/generate-parentheses/description/
如果有收获,可以请我喝杯咖啡!