-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCombinationsThatSumToTarget.java
More file actions
59 lines (55 loc) · 2.21 KB
/
CombinationsThatSumToTarget.java
File metadata and controls
59 lines (55 loc) · 2.21 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
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
class CombinationsThatSumToTarget {
private Map<Integer, List<List<Integer>>> cache;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
cache = new HashMap<>();
return _combinationSum(candidates, target);
}
List<List<Integer>> _combinationSum(int[] candidates, int target) {
if (cache.containsKey(target))
return cache.get(target);
int min = candidates[0];
boolean sameValueFound = false;
for (int i = 0; i < candidates.length; i++) {
if (min > candidates[i])
min = candidates[i];
if (target == candidates[i])
sameValueFound = true;
}
if (target < min)
return new ArrayList<>();
List<List<Integer>> list = new ArrayList<>();
if (sameValueFound)
list.add(new ArrayList<>(Arrays.asList(target)));
for (int i = 0; i < candidates.length; i++) {
if (target > candidates[i]) {
int newTarget = target - candidates[i];
System.out.println("New target: " + newTarget);
List<List<Integer>> subList = combinationSum(candidates, newTarget);
System.out.println(subList);
for (List<Integer> sub : subList) {
System.out.println("The last melon: " + sub.get(sub.size() - 1));
System.out.println("candidates[" + i + "]: " + candidates[i]);
if (sub.get(sub.size() - 1) <= candidates[i]) {
List<Integer> newSub = new ArrayList<>(sub);
newSub.add(candidates[i]);
list.add(newSub);
}
}
}
}
cache.put(target, list);
return list;
}
public static void main(String[] args) {
CombinationsThatSumToTarget ctstt = new CombinationsThatSumToTarget();
int[] candidates = {2, 3, 6, 7};
int target = 7;
List<List<Integer>> list = ctstt.combinationSum(candidates, target);
System.out.println(list);
}
}