-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0022-generate-parentheses.cpp
More file actions
46 lines (34 loc) · 1009 Bytes
/
0022-generate-parentheses.cpp
File metadata and controls
46 lines (34 loc) · 1009 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
46
#include <string>
#include <vector>
class Solution {
private:
const static char left_parenthese = '(';
const static char right_parenthese = ')';
int length;
public:
void dfs(std::string base, int left, int right, std::vector<std::string> &result){
if (left == this->length and right == this->length) {
result.push_back(base);
return;
}
if (left < right) {
// 剩下未使用的左括号多于右括号
return;
}
if (left < this->length) {
dfs(base + this->left_parenthese, left + 1, right, result);
}
if (right < this->length) {
dfs(base + this->right_parenthese, left, right + 1, result);
}
}
std::vector<std::string> generateParenthesis(int n) {
std::vector<std::string> result;
if (n == 0) {
return result;
}
this->length = n;
dfs("", 0, 0, result);
return result;
}
};