[LeetCode][JavaScript]Combination Sum II
Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
https://leetcode.com/problems/combination-sum-ii/
有了上一道的基础,这道妥妥的。
http://www.cnblogs.com/Liok3187/p/4526863.html
说数字不能重复用,于是就从index + 1开始循环,但是这样会出现重复的数据。
比如例子中的[1,7]和[1,2,5],他们的1可以是第一个1也可以是第二个1。
我就粗暴地加了一个vistied变量去重...
1 /** 2 * @param {number[]} candidates 3 * @param {number} target 4 * @return {number[][]} 5 */ 6 var combinationSum2 = function(candidates, target) { 7 var res = []; 8 var visited = new Set(); 9 candidates.sort(sorting); 10 bfs(0, -1, []); 11 return res; 12 13 function bfs(sum, index, tmp){ 14 var current = tmp.join('#'); 15 if(visited.has(current)){ 16 return; 17 }else{ 18 visited.add(current); 19 } 20 21 var newTmp = null; 22 if(sum === target){ 23 newTmp = tmp.concat(); 24 res.push(newTmp); 25 return; 26 }else if(sum > target || index + 1 >= candidates.length){ 27 return; //pruning 28 } 29 30 for(var i = index + 1; i < candidates.length; i++){ 31 newTmp = tmp.concat(); 32 newTmp.push(candidates[i]); 33 bfs(sum + candidates[i], i, newTmp); 34 } 35 } 36 function sorting(a, b){ 37 if(a > b){ 38 return 1; 39 }else if(a < b){ 40 return -1; 41 }else{ 42 return 0; 43 } 44 } 45 };