forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
40-Combination-Sum-II.js
52 lines (46 loc) · 1.33 KB
/
40-Combination-Sum-II.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
//////////////////////////////////////////////////////////////////////////////
// Backtracking
// Time: Theta(2^log(n)) O(2^n)
// Space: Theta(2^log(n)) O(2^n)
//////////////////////////////////////////////////////////////////////////////
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
function combinationSum2(candidates, target) {
candidates.sort((a, b) => a - b);
const combos = [];
const combo = [];
const map = Object.create(null);
for (let i = 0; i < candidates.length; ++i) {
map[candidates[i]] = i;
}
getCombos(target);
return combos;
/**
* @param {number} target
* @param {number=} start = `0`
* @return {void}
*/
function getCombos(target, start = 0) {
if (target in map && start <= map[target]) {
combo.push(target);
combos.push(combo.slice());
combo.pop();
}
const mid = Math.floor(target / 2);
for (
let i = start;
i < candidates.length && candidates[i] <= mid;
++i
) {
if (i !== start && candidates[i] === candidates[i - 1]) {
continue;
}
combo.push(candidates[i]);
getCombos(target - candidates[i], i + 1);
combo.pop();
}
}
}