-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcombinationSum2.js
More file actions
35 lines (30 loc) · 846 Bytes
/
combinationSum2.js
File metadata and controls
35 lines (30 loc) · 846 Bytes
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
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var addThemUp = function(array){
return array.reduce(function(prev, current){return prev + current}, 0);
}
var combinationSum2 = function(candidates, target) {
var results = [];
candidates.sort(function(a, b){return b - a});
var findTotals = function(current, pullFrom){
if (addThemUp(current) === target){
current.sort(function(a, b){return a-b});
results.push(current.slice());
return;
}else if (addThemUp(current) > target){
return;
}
for (var i = 0; i < pullFrom.length; i++){
var temp = pullFrom.splice(i, 1)[0];
current.push(temp);
findTotals(current, pullFrom);
current.pop();
pullFrom.splice(i, 0, temp);
}
}
findTotals([], candidates);
return results;
};