|
| 1 | +### [40\. Combination Sum IICopy for MarkdownCopy for MarkdownCopy for Markdown](https://leetcode.com/problems/combination-sum-ii/) |
| 2 | + |
| 3 | +Difficulty: **Medium** |
| 4 | + |
| 5 | + |
| 6 | +Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sums to `target`. |
| 7 | + |
| 8 | +Each number in `candidates` may only be used **once** in the combination. |
| 9 | + |
| 10 | +**Note:** |
| 11 | + |
| 12 | +* All numbers (including `target`) will be positive integers. |
| 13 | +* The solution set must not contain duplicate combinations. |
| 14 | + |
| 15 | +**Example 1:** |
| 16 | + |
| 17 | +``` |
| 18 | +Input: candidates = [10,1,2,7,6,1,5], target = 8, |
| 19 | +A solution set is: |
| 20 | +[ |
| 21 | + [1, 7], |
| 22 | + [1, 2, 5], |
| 23 | + [2, 6], |
| 24 | + [1, 1, 6] |
| 25 | +] |
| 26 | +``` |
| 27 | + |
| 28 | +**Example 2:** |
| 29 | + |
| 30 | +``` |
| 31 | +Input: candidates = [2,5,2,1,2], target = 5, |
| 32 | +A solution set is: |
| 33 | +[ |
| 34 | + [1,2,2], |
| 35 | + [5] |
| 36 | +] |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +#### Solution |
| 41 | + |
| 42 | +Language: **Java** |
| 43 | + |
| 44 | +```java |
| 45 | +class Solution { |
| 46 | + public List<List<Integer>> combinationSum2(int[] candidates, int target) { |
| 47 | + Arrays.sort(candidates); |
| 48 | + Set<List<Integer>> result = new HashSet<>(); |
| 49 | + for (int i = 0; i < candidates.length; i++) { |
| 50 | + if (i > 1 && candidates[i] == candidates[i - 1]) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + if (target == candidates[i]) { |
| 54 | + result.add(Collections.singletonList(target)); |
| 55 | + } |
| 56 | + for (List<Integer> list : this.combinationSum2(candidates, i, target - candidates[i])) { |
| 57 | + list.add(candidates[i]); |
| 58 | + result.add(list); |
| 59 | + } |
| 60 | + } |
| 61 | + return new ArrayList<>(result); |
| 62 | + } |
| 63 | + |
| 64 | + private List<List<Integer>> combinationSum2(int[] candidates, int index, int target) { |
| 65 | + List<List<Integer>> result = new ArrayList<>(); |
| 66 | + if (target < candidates[index]) { |
| 67 | + return result; |
| 68 | + } |
| 69 | + if (Arrays.binarySearch(candidates, index + 1, candidates.length, target) > 0) { |
| 70 | + result.add(new ArrayList<>(Collections.singletonList(target))); |
| 71 | + } |
| 72 | + for (int i = index + 1; i < candidates.length; i++) { |
| 73 | + for (List<Integer> list : this.combinationSum2(candidates, i, target - candidates[i])) { |
| 74 | + list.add(candidates[i]); |
| 75 | + result.add(list); |
| 76 | + } |
| 77 | + } |
| 78 | + return result; |
| 79 | + } |
| 80 | +} |
| 81 | + for (List<Integer> list : this.combinationSum2(candidates, i, target - candidates[i])) { |
| 82 | +``` |
| 83 | + |
0 commit comments