-
Notifications
You must be signed in to change notification settings - Fork 0
/
combination-sum-ii.java
60 lines (50 loc) · 1.96 KB
/
combination-sum-ii.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
// Problem link - https://leetcode.com/problems/combination-sum-ii/description/
// TC - O(2^N)
// SC - O(N)
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
LinkedList<Integer> combination = new LinkedList<>();
HashMap<Integer, Integer> counter = new HashMap<>();
for (int candidate : candidates) {
if (counter.containsKey(candidate)) counter.put(
candidate,
counter.get(candidate) + 1
);
else counter.put(candidate, 1);
}
List<int[]> counterList = new ArrayList<>();
counter.forEach((key, value) -> {
counterList.add(new int[] { key, value });
});
helper(combination, target, 0, counterList, combinations);
return combinations;
}
private void helper(
LinkedList<Integer> combination,
int target,
int pos,
List<int[]> counter,
List<List<Integer>> combinations
) {
if (target <= 0) {
if (target == 0) {
combinations.add(new ArrayList<Integer>(combination));
}
return;
}
for (int nextCurr = pos; nextCurr < counter.size(); ++nextCurr) {
int[] entry = counter.get(nextCurr);
Integer candidate = entry[0], freq = entry[1];
if (freq <= 0) continue;
// add a new element to the current combination
combination.addLast(candidate);
counter.set(nextCurr, new int[] { candidate, freq - 1 });
// continue the exploration with the updated combination
helper(combination, target - candidate, nextCurr, counter, combinations);
// helper the changes, so that we can try another candidate
counter.set(nextCurr, new int[] { candidate, freq });
combination.removeLast();
}
}
}