-
Notifications
You must be signed in to change notification settings - Fork 0
/
22.括号生成.cpp
93 lines (84 loc) · 1.44 KB
/
22.括号生成.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* @lc app=leetcode.cn id=22 lang=cpp
*
* [22] 括号生成
*/
#include <iostream>
using namespace std;
// @lc code=start
class Solution {
private:
string s;
int n;
vector<string> ans;
void dfs(int i) {
if (i == 2 * n) {
if (isValid(s)) ans.push_back(s);
return;
}
s.push_back('(');
dfs(i + 1);
s.pop_back();
s.push_back(')');
dfs(i + 1);
s.pop_back();
}
bool isValid(string &s) {
int left = 0;
for (char ch : s) {
if (ch == '(')
left++;
else {
if (left <= 0) return false;
left--;
}
}
return left == 0;
}
/**
* 剪枝
*/
void dfs2(int i, int left, int right) {
if (left > n || right > n || !isValid2(s)) return;
if (i == 2 * n) {
ans.push_back(s);
return;
}
s.push_back('(');
dfs2(i + 1, left + 1, right);
s.pop_back();
s.push_back(')');
dfs2(i + 1, left, right + 1);
s.pop_back();
}
bool isValid2(string &s) {
int left = 0;
for (char ch : s) {
if (ch == '(')
left++;
else {
if (left <= 0) return false;
left--;
}
}
return true;
}
public:
/**
* 暴力递归
*/
vector<string> generateParenthesis2(int n) {
this->n = n;
dfs(0);
return ans;
}
/**
* 剪枝优化
*/
vector<string> generateParenthesis(int n) {
this->n = n;
dfs2(0, 0, 0);
return ans;
}
};
// @lc code=end