-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLeetCode77.java
84 lines (76 loc) · 2.37 KB
/
LeetCode77.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
80
81
82
83
84
package problems;
import java.util.*;
public class LeetCode77 {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if(k<=0 || n<k){
return res;
}
List<Integer> path = new ArrayList<>();
dfs(res, path, n, k, 1);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> path, int n , int k, int begin){
// 递归终止条件:path的长度等于K
if(path.size() == k){
res.add(new ArrayList<>(path));
return;
}
// (int i=begin;i<n;i++)
// 还可以进行剪枝
for(int i=begin;i<=n-(k-path.size())+1;i++){
path.add(i);
dfs(res, path, n, k, i+1);
path.remove(path.size()-1);
}
}
}
class LeetCode77_1 {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
dfs(ans, path, n, 1, k);
return ans;
}
private void dfs(List<List<Integer>> ans, Deque<Integer> path, int n, int index, int k) {
if(k == path.size()) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = index; i <= n; i++) {
path.add(i);
dfs(ans, path, n, i + 1, k);
path.removeLast();
}
}
}
class LeetCode77_2 {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
dfs(res, ans, n, k, 1);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> ans, int n, int k, int index) {
if(ans.size() == k) {
res.add(new ArrayList<>(ans));
return;
}
for (int i = index; i <= n; i++) {
ans.add(i);
dfs(res, ans, n, k, i + 1);
ans.remove(ans.size() - 1);
}
}
private void dfsOptimization(List<List<Integer>> res, List<Integer> ans, int n, int k, int index) {
if(ans.size() == k) {
res.add(new ArrayList<>(ans));
return;
}
for (int i = index; i <= n - (k - ans.size()); i++) {
ans.add(i);
dfsOptimization(res, ans, n, k, i + 1);
ans.remove(ans.size() - 1);
}
}
}