-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLeetCode216.java
More file actions
68 lines (60 loc) · 1.8 KB
/
LeetCode216.java
File metadata and controls
68 lines (60 loc) · 1.8 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
package problems;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LeetCode216 {
public List<List<Integer>> combinationSum3(int k, int n) {
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() + (n - index + 1) < k || ans.size() > k) {
return;
}
if(ans.size() == k) {
int tempSum = 0;
for (int sum : ans) {
tempSum += sum;
}
if(n == tempSum) {
res.add(new ArrayList<>(ans));
return;
}
}
for (int i = index; i <= 9 && k > 0; i++) {
ans.add(i);
dfs(res, ans, n, k, i + 1);
ans.remove(ans.size() - 1);
}
}
}
class LeetCode216_1 {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int k, int n) {
backTracking(n, k, 1, 0);
return result;
}
private void backTracking(int targetSum, int k, int startIndex, int sum) {
// 减枝
if (sum > targetSum) {
return;
}
if (path.size() == k) {
if (sum == targetSum) result.add(new ArrayList<>(path));
return;
}
// 减枝 9 - (k - path.size()) + 1
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.add(i);
sum += i;
backTracking(targetSum, k, i + 1, sum);
//回溯
path.removeLast();
//回溯
sum -= i;
}
}
}