-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22.java
75 lines (62 loc) · 1.5 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
class Solution {
private char[] path;
private final List<String> ans = new ArrayList<>();
private int n;
public List<String> generateParenthesis(int n) {
this.n = n;
path = new char[n * 2]; // 所有括号长度都是一样的 n*2
dfs(0, 0);
return ans;
}
private void dfs(int i, int num) {
if (i == n * 2) {
ans.add(new String(path));
return;
}
// 选左括号
if (num < n) {
path[i]='(';
dfs(i + 1, num + 1);
}
// 选右括号
if (i - num < num) {
path[i]=')';
dfs(i + 1, num);
}
}
}
// 第二次自己的做法
class Solution {
private List<String> ans = new ArrayList<>();
private StringBuilder path = new StringBuilder();
private int n;
public List<String> generateParenthesis(int n) {
this.n = n;
dfs(0, 0);
return ans;
}
private void dfs(int l, int r) {
if (l == n && r == n) {
ans.add(new String(path));
return;
}
if (l == 0) {
path.append("(");
l++;
}
if (l < n) {
path.append("(");
l++;
dfs(l, r);
l--;
path.setLength(path.length()-1);
}
if (r < n&&l>r) {
path.append(")");
r++;
dfs(l, r);
r--;
path.setLength(path.length()-1);
}
}
}