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
| class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> resultList = new ArrayList<>();
Arrays.sort(candidates); List<Integer> numList = new ArrayList<>(); dfs(resultList, numList, candidates, 0, false, 0, target); return resultList; }
private void dfs(List<List<Integer>> resultList, List<Integer> numList, int[] candidates, int i, boolean chosenPre, int sum, int target) { if (sum > target) { return; } if (i == candidates.length) { if (sum == target) { resultList.add(new ArrayList<>(numList)); } return; }
dfs(resultList, numList, candidates, i + 1, false, sum, target);
if (i > 0 && candidates[i] == candidates[i - 1] && !chosenPre) { return; }
numList.add(candidates[i]); dfs(resultList, numList, candidates, i + 1, true, sum + candidates[i], target); numList.remove(numList.size() - 1); } }
|