forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParenthesis_22.java
More file actions
94 lines (83 loc) · 2.67 KB
/
Copy pathGenerateParenthesis_22.java
File metadata and controls
94 lines (83 loc) · 2.67 KB
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
94
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class GenerateParenthesis_22 {
/**
* 1、使用dfs先遍历所有的组合
* 2、使用栈来验证每种组合的有效性
* @param n
* @return
*/
// 1、注意这里使用foreach遍历list删除元素会抛java.util.ConcurrentModificationException异常,改用迭代器遍历删除
public List<String> generateParenthesis1(int n) {
List<String> list = new ArrayList<>();
dfs1(n, "", list);
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
if (!checkPath(iterator.next())) {
iterator.remove();
}
}
return list;
}
private void dfs1(int n, String path, List<String> list) {
if (path.length() == n * 2) {
list.add(path);
return;
}
dfs1(n, path + "(", list);
dfs1(n, path + ")", list);
}
private boolean checkPath(String path) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '(') {
stack.push("(");
} else if (stack.isEmpty()) {
return false;
} else {
stack.pop();
}
}
return stack.isEmpty();
}
/**
* 通过剪枝策略优化以上解法
* @param n
*/
public List<String> generateParenthesis2(int n) {
List<String> list = new ArrayList<>();
if (n <= 0) {
return list;
}
dfs2("", list, n, n);
return list;
}
/**
* @param path 当前递归得到的结果
* @param list 结果集
* @param leftCount 左括号还有几个可以使用
* @param rightCount 右括号还有几个可以使用
*/
private void dfs2(String path, List<String> list, int leftCount, int rightCount) {
if (leftCount == 0 && rightCount == 0) {
list.add(path);
return;
}
// 剪枝策略:去掉右边括号剩下的数量比左边括号少的情况
if (rightCount < leftCount) {
return;
}
if (leftCount > 0) {
dfs2(path + "(", list, leftCount - 1, rightCount);
}
if (rightCount > 0) {
dfs2(path + ")", list, leftCount, rightCount - 1);
}
// 每次尝试都是使用的新的字符串变量,无需回溯
}
public static void main(String[] args) {
System.out.println(new GenerateParenthesis_22().generateParenthesis2(2));
}
}