-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22.括号生成.java
79 lines (70 loc) · 1.49 KB
/
22.括号生成.java
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
import java.util.ArrayList;
import java.util.List;
/*
* @lc app=leetcode.cn id=22 lang=java
*
* [22] 括号生成
*/
// @lc code=start
class Solution {
private int n;
private char[] str;
private int idx = 0;
private ArrayList<String> res = new ArrayList<>();
private int unclosed = 0;
private void push(char c) {
str[idx++] = c;
}
private void pop() {
idx--;
}
private int size() {
return idx;
}
private void open() {
push('(');
unclosed++;
}
private boolean close() {
if (unclosed == 0) {
return false;
}
push(')');
unclosed--;
return true;
}
public void pushOne(int left) {
if (size() == n * 2) {
if (unclosed == 0) {
res.add(new String(str));
}
return;
}
if (left == 0) {
// 只能闭合
if (close()) {
pushOne(left);
pop();
unclosed++;
}
} else {
// 开放或者闭合
open();
pushOne(left - 1);
pop();
unclosed--;
if (close()) {
pushOne(left);
pop();
unclosed++;
}
}
}
public List<String> generateParenthesis(int n) {
this.n = n;
this.str = new char[n * 2];
pushOne(n);
return res;
}
}
// @lc code=end