-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcombinationSumTwo.js
81 lines (75 loc) · 2.18 KB
/
combinationSumTwo.js
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
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
//一开始用hash = {}来去重,慢了很多。以后尽量少用这个来去重
var ans,
res;
var combinationSum2 = function(candidates, target) {
res = [];
candidates.sort(function(a, b){
return a - b;
});
for(var i = 0; i < candidates.length; i++){
if(i && candidates[i] === candidates[i -1]) continue;
ans = [candidates[i]];
search(i + 1, candidates[i], candidates, target);
}
return res;
};
function search(index, sum, candidates, target){
if(sum === target){
var temp = ans.map(function(item){
return item;
});
res.push(temp);
return;
}
for(var i = index; i < candidates.length; i++){
if(sum + candidates[i] > target) break;
if(i > index && candidates[i] === candidates[i - 1]) continue;
ans.push(candidates[i]);
search(i + 1, sum + candidates[i], candidates, target);
ans.pop();
}
}
console.log(combinationSum2([10, 1, 2, 7, 6, 1, 5],8));
console.log(combinationSum2([2,2,2,2],4));
console.log(combinationSum2([1,1],1));
//hash去重,还有就是leetcode在测试多个test的时候只是调用了函数,所以全局变量不会改变。
//所以hash要在主函数里面初始化。
// var ans,
// res,
// hash;
// var combinationSum2 = function(candidates, target) {
// hash = {};
// res = [];
// candidates.sort(function(a, b){
// return a - b;
// });
// for(var i = 0; i < candidates.length; i++){
// //if(i && candidates[i] === candidates[i -1]) continue;
// ans = [candidates[i]];
// search(i + 1, candidates[i], candidates, target);
// }
// return res;
// };
// function search(index, sum, candidates, target){
// if(sum === target){
// var temp = ans.map(function(item){
// return item;
// });
// if(!hash[temp]){
// res.push(temp);
// hash[temp] = true;
// }
// return;
// }
// for(var i = index; i < candidates.length; i++){
// if(sum + candidates[i] > target) break;
// ans.push(candidates[i]);
// search(i + 1, sum + candidates[i], candidates, target);
// ans.pop();
// }
// }