-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum-ii.js
More file actions
41 lines (37 loc) · 931 Bytes
/
combination-sum-ii.js
File metadata and controls
41 lines (37 loc) · 931 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
36
37
38
39
40
41
/**
* 40. 组合总和 II
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
candidates.sort((a, b) => a - b);
const result = [];
const path = [];
let sum = 0;
// [1,1,2,5,6,7,10]
const backtracking = (candidates, target, startIndex) => {
if (sum === target) {
result.push(path.slice());
return;
}
for (
let i = startIndex;
i < candidates.length && sum + candidates[i] <= target; // 剪枝
i++
) {
// 要对同一树层使用过的元素进行跳过
if (i > startIndex && candidates[i] === candidates[i - 1]) {
continue;
}
const curr = candidates[i];
path.push(curr);
sum += curr;
backtracking(candidates, target, i + 1);
sum -= curr;
path.pop();
}
};
backtracking(candidates, target, 0);
return result;
};