|
| 1 | +# 40. Combination Sum II |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Backtracking. |
| 5 | +- Similar Questions: Combination Sum. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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```. |
| 10 | + |
| 11 | +Each number in ```candidates``` may only be used **once** in the combination. |
| 12 | + |
| 13 | +**Note:** |
| 14 | + |
| 15 | +- All numbers (including ```target```) will be positive integers. |
| 16 | +- The solution set must not contain duplicate combinations. |
| 17 | + |
| 18 | +**Example 1:** |
| 19 | + |
| 20 | +``` |
| 21 | +Input: candidates = [10,1,2,7,6,1,5], target = 8, |
| 22 | +A solution set is: |
| 23 | +[ |
| 24 | + [1, 7], |
| 25 | + [1, 2, 5], |
| 26 | + [2, 6], |
| 27 | + [1, 1, 6] |
| 28 | +] |
| 29 | +``` |
| 30 | + |
| 31 | +**Example 2:** |
| 32 | + |
| 33 | +``` |
| 34 | +Input: candidates = [2,5,2,1,2], target = 5, |
| 35 | +A solution set is: |
| 36 | +[ |
| 37 | + [1,2,2], |
| 38 | + [5] |
| 39 | +] |
| 40 | +``` |
| 41 | + |
| 42 | +## Solution |
| 43 | + |
| 44 | +```javascript |
| 45 | +/** |
| 46 | + * @param {number[]} candidates |
| 47 | + * @param {number} target |
| 48 | + * @return {number[][]} |
| 49 | + */ |
| 50 | +var combinationSum2 = function(candidates, target) { |
| 51 | + var res = []; |
| 52 | + var len = candidates.length; |
| 53 | + candidates.sort((a, b) => (a - b)); |
| 54 | + dfs(res, [], 0, len, candidates, target); |
| 55 | + return res; |
| 56 | +}; |
| 57 | + |
| 58 | +var dfs = function (res, stack, index, len, candidates, target) { |
| 59 | + var tmp = null; |
| 60 | + if (target < 0) return; |
| 61 | + if (target === 0) return res.push(stack); |
| 62 | + for (var i = index; i < len; i++) { |
| 63 | + if (candidates[i] > target) break; |
| 64 | + if (i > index && candidates[i] === candidates[i - 1]) continue; |
| 65 | + tmp = Array.from(stack); |
| 66 | + tmp.push(candidates[i]); |
| 67 | + dfs(res, tmp, i + 1, len, candidates, target - candidates[i]); |
| 68 | + } |
| 69 | +}; |
| 70 | +``` |
| 71 | + |
| 72 | +**Explain:** |
| 73 | + |
| 74 | +与之前一题不同的地方是: |
| 75 | + |
| 76 | +1. 候选数字可能有重复的 |
| 77 | +2. 单个候选数字不能重复使用 |
| 78 | + |
| 79 | +**Complexity:** |
| 80 | + |
| 81 | +* Time complexity : O(n^2). |
| 82 | +* Space complexity : O(n^2). |
0 commit comments