|
| 1 | +package problems.leetcode; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Collection; |
| 7 | +import java.util.Collections; |
| 8 | +import java.util.Deque; |
| 9 | +import java.util.HashMap; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +// https://leetcode.com/problems/combination-sum-ii/ |
| 14 | +public class CombinationSumII { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + for (List<Integer> l : combinationSum2(new int[] { 10, 1, 2, 2, 2, 2, 7, 6, 1, 1, 5 }, 8)) { |
| 18 | + System.out.println(l); |
| 19 | + } |
| 20 | + |
| 21 | + // for (List<Integer> l : combinationSum2(new int[] { 10, 1, 2, 2, 7, 6, 1, 1, 5 |
| 22 | + // }, 8)) { |
| 23 | + // System.out.println(l); |
| 24 | + // } |
| 25 | + } |
| 26 | + |
| 27 | + // 1, 1, 1, 2, 2, 5, 6, 7, 10 target = 8 |
| 28 | + |
| 29 | + public static List<List<Integer>> combinationSum2(int[] candidates, int target) { |
| 30 | + // container to hold the final combinations |
| 31 | + List<List<Integer>> results = new ArrayList<>(); |
| 32 | + Deque<Integer> comb = new ArrayDeque<>(); |
| 33 | + Map<Integer, Integer> counter = new HashMap<>(); |
| 34 | + for (int candidate : candidates) { |
| 35 | + counter.compute(candidate, (k, v) -> v != null ? v + 1 : 1); |
| 36 | + } |
| 37 | + |
| 38 | + // convert the counter table to a list of (num, count) tuples |
| 39 | + List<int[]> counterList = new ArrayList<>(); |
| 40 | + counter.forEach((key, value) -> { |
| 41 | + counterList.add(new int[] { key, value }); |
| 42 | + }); |
| 43 | + |
| 44 | + backtrack(comb, target, 0, counterList, results); |
| 45 | + return results; |
| 46 | + } |
| 47 | + |
| 48 | + private static void backtrack(Deque<Integer> comb, |
| 49 | + int target, int i, |
| 50 | + List<int[]> counter, |
| 51 | + List<List<Integer>> results) { |
| 52 | + if (target == 0) { |
| 53 | + // make a deep copy of the current combination. |
| 54 | + results.add(new ArrayList<Integer>(comb)); |
| 55 | + return; |
| 56 | + } else if (target < 0) { |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + for (int j = i; j < counter.size(); j++) { |
| 61 | + int[] entry = counter.get(j); |
| 62 | + int candidate = entry[0], freq = entry[1]; |
| 63 | + if (freq <= 0) { |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + // add a new element to the current combination |
| 68 | + comb.addLast(candidate); |
| 69 | + entry[1]--; |
| 70 | + |
| 71 | + // continue the exploration with the updated combination |
| 72 | + backtrack(comb, target - candidate, j, counter, results); |
| 73 | + |
| 74 | + // backtrack the changes, so that we can try another candidate |
| 75 | + entry[1]++; |
| 76 | + comb.removeLast(); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments