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
| package algorithm;
import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class CombinationSumII {
static List<int []> freq = new ArrayList<>(); static List<List<Integer>> ans = new ArrayList<>(); static List<Integer> sequence = new ArrayList<>();
public static List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates);
for (int candidate : candidates) { if (freq.isEmpty() || freq.get(freq.size() - 1)[0] != candidate) { freq.add(new int[]{candidate, 1}); } else { ++freq.get(freq.size() - 1)[1]; } } dfs(0, target); return ans; }
private static void dfs(int pos, int target) { if (target == 0) { ans.add(new ArrayList<>(sequence)); } if (pos == freq.size() || target < freq.get(pos)[0]) { return; } // 跳过 dfs(pos + 1, target);
int most = Math.min(target / freq.get(pos)[0], freq.get(pos)[1]); for (int i = 1; i <= most; i++) { sequence.add(freq.get(pos)[0]); // 虽然每次都会循环,但是pos都不变,也就是每次从下一个为为孩子开始,但是重复数字会叠加 dfs(pos + 1, target - i * freq.get(pos)[0]); } for (int i = 1; i <= most; i++) { sequence.remove(sequence.size() - 1); } }
public static void main(String[] args) {
int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5}; int targe = 8; System.out.println(combinationSum2(candidates, targe));
candidates = new int[]{2, 5, 2, 1, 2}; targe = 5; System.out.println(combinationSum2(candidates, targe)); } }
|