|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Arrays; |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +class Solution { |
| 10 | + private HashMap<Integer, List<String>> dp = new HashMap<>(); |
| 11 | + private HashSet<Integer> set; |
| 12 | + |
| 13 | + public List<List<Integer>> combinationSum(int[] candidates, int target) { |
| 14 | + set = new HashSet<>(Arrays.stream(candidates).boxed().toList()); |
| 15 | + recurse(target); |
| 16 | + // Convert dp entries back to List<List<Integer>> for return |
| 17 | + return dp.getOrDefault(target, new ArrayList<>()).stream() |
| 18 | + .map(str -> Arrays.stream(str.split(" ")) |
| 19 | + .map(Integer::valueOf) |
| 20 | + .collect(Collectors.toList())) |
| 21 | + .collect(Collectors.toList()); |
| 22 | + } |
| 23 | + |
| 24 | + public void recurse(int target) { |
| 25 | + if (dp.containsKey(target)) return; |
| 26 | + |
| 27 | + List<String> combinations = new ArrayList<>(); |
| 28 | + for (int i = 1; i < target + 1; i++) { |
| 29 | + if (set.contains(i)) { |
| 30 | + int remaining = target - i; |
| 31 | + recurse(remaining); |
| 32 | + if (dp.containsKey(remaining)) { |
| 33 | + for (String combination : dp.get(remaining)) { |
| 34 | + List<Integer> newCombination = new ArrayList<>(Arrays.stream(combination.split(" ")) |
| 35 | + .map(Integer::valueOf) |
| 36 | + .toList()); |
| 37 | + newCombination.add(i); |
| 38 | + newCombination.sort(Comparator.reverseOrder()); |
| 39 | + |
| 40 | + String newCombinationStr = newCombination.stream() |
| 41 | + .map(String::valueOf) |
| 42 | + .collect(Collectors.joining(" ")); |
| 43 | + if (!combinations.contains(newCombinationStr)) { |
| 44 | + combinations.add(newCombinationStr); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + if (set.contains(target)) { |
| 51 | + String singleCombination = String.valueOf(target); |
| 52 | + if (!combinations.contains(singleCombination)) { |
| 53 | + combinations.add(singleCombination); |
| 54 | + } |
| 55 | + } |
| 56 | + dp.put(target, combinations); |
| 57 | + } |
| 58 | + |
| 59 | +} |
| 60 | + |
0 commit comments