forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
39-Combination-Sum.js
44 lines (41 loc) · 1.19 KB
/
39-Combination-Sum.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
//////////////////////////////////////////////////////////////////////////////
// Backtracking
// Time: Theta(log(n)^(target/min)) O(n^(target/min))
// Space: Theta(log(n)*(target/min)^2) O(n*(target/min)^2)
//////////////////////////////////////////////////////////////////////////////
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
function combinationSum(candidates, target) {
candidates.sort((a, b) => a - b);
const combos = [];
const combo = [];
const set = new Set(candidates);
buildCombos(target);
return combos;
/**
* @param {number} target
* @param {number=} start = `0`
* @return {void}
*/
function buildCombos(target, start = 0) {
if (set.has(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
) {
const candidate = candidates[i];
combo.push(candidate);
buildCombos(target - candidate, i);
combo.pop();
}
}
}