-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCombinationSum.java
85 lines (67 loc) · 2.51 KB
/
CombinationSum.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
85
package leetcode.sum;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class CombinationSum {
// Pre-condition: There is no duplicate in the input array.
public List<List<Integer>> combinationSum(int[] candidates, int target) {
return combinationSum(candidates, 0, target);
}
private List<List<Integer>> combinationSum(int[] candidates, int startFrom, int target) {
List<List<Integer>> result = new LinkedList<>();
// Returns for invalid cases.
if (startFrom >= candidates.length || target < 0) {
return result;
} else if (target == 0) {
result.add(new LinkedList<>());
return result;
}
int current = candidates[startFrom];
// Uses the current element.
for (List<Integer> group: combinationSum(candidates, startFrom, target - current)) {
group.add(current);
result.add(group);
}
// Not uses the current element.
result.addAll(combinationSum(candidates, startFrom + 1, target));
return result;
}
// Notice: there may be duplicates in the input.
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
return combinationSum2(candidates, 0, target);
}
private List<List<Integer>> combinationSum2(int[] candidates, int startFrom, int target) {
List<List<Integer>> result = new LinkedList<>();
// Returns for invalid cases.
if (startFrom >= candidates.length || target < 0) {
return result;
} else if (target == 0) {
result.add(new LinkedList<>());
return result;
}
int current = candidates[startFrom];
// Uses the current element.
for (List<Integer> group: combinationSum2(candidates, startFrom + 1, target - current)) {
group.add(current);
result.add(group);
}
// Not uses the current element.
result.addAll(combinationSum2(candidates, startFrom + 1, target));
return result;
}
public int combinationSum4(int[] nums, int target) {
int[] count = new int[target + 1];
count[0] = 1;
for (int i = 1; i <= target; i++) {
int current = 0;
for (int num: nums) {
if (i >= num) {
current += count[i - num];
}
}
count[i] = current;
}
return count[target];
}
}