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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import java.util.*;
public class _40组合总和II {
List<int[]> freq = new ArrayList<int[]>(); List<List<Integer>> ans = new ArrayList<List<Integer>>(); List<Integer> sequence = new ArrayList<Integer>();
public List<List<Integer>> combinationSum2_gov(int[] candidates, int target) { Arrays.sort(candidates); for (int num : candidates) { int size = freq.size(); if (freq.isEmpty() || num != freq.get(size - 1)[0]) { freq.add(new int[]{num, 1}); } else { ++freq.get(size - 1)[1]; } } dfs(0, target); return ans; }
public void dfs(int pos, int rest) { if (rest == 0) { ans.add(new ArrayList<Integer>(sequence)); return; } if (pos == freq.size() || rest < freq.get(pos)[0]) { return; }
dfs(pos + 1, rest);
int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]); for (int i = 1; i <= most; ++i) { sequence.add(freq.get(pos)[0]); dfs(pos + 1, rest - i * freq.get(pos)[0]); } for (int i = 1; i <= most; ++i) { sequence.remove(sequence.size() - 1); } }
public List<List<Integer>> combinationSum2_lookback(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<>(); dfs(candidates, target, -1, new ArrayList<>(), res); return res; }
private void dfs(int[] candidates, int target, int idx, List<Integer> list, List<List<Integer>> res) { if (target == 0) { res.add(new ArrayList<>(list)); return; }
for (int i = idx + 1; i < candidates.length; i++) { int nextTarget = target - candidates[i]; if (nextTarget < 0) return; if (i != idx + 1 && candidates[i - 1] == candidates[i]) { continue; } list.addLast(candidates[i]); dfs(candidates, target - candidates[i], i, list, res); list.removeLast(); } }
public static void main(String[] args) { _40组合总和II combinationSum2 = new _40组合总和II(); System.out.println(combinationSum2.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8)); System.out.println(combinationSum2.combinationSum2_lookback(new int[]{10, 1, 2, 7, 6, 1, 5}, 8)); } }
|