Skip to content

Commit c683c83

Browse files
committed
Added JS solution for problem 40
1 parent 07f1cee commit c683c83

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Backtracking
3+
// Time: Theta(2^log(n)) O(2^n)
4+
// Space: Theta(2^log(n)) O(2^n)
5+
//////////////////////////////////////////////////////////////////////////////
6+
7+
/**
8+
* @param {number[]} candidates
9+
* @param {number} target
10+
* @return {number[][]}
11+
*/
12+
function combinationSum2(candidates, target) {
13+
14+
candidates.sort((a, b) => a - b);
15+
16+
const combos = [];
17+
const combo = [];
18+
const map = Object.create(null);
19+
20+
for (let i = 0; i < candidates.length; ++i) {
21+
map[candidates[i]] = i;
22+
}
23+
24+
getCombos(target);
25+
return combos;
26+
27+
/**
28+
* @param {number} target
29+
* @param {number=} start = `0`
30+
* @return {void}
31+
*/
32+
function getCombos(target, start = 0) {
33+
34+
if (target in map && start <= map[target]) {
35+
combo.push(target);
36+
combos.push(combo.slice());
37+
combo.pop();
38+
}
39+
40+
const mid = Math.floor(target / 2);
41+
for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) {
42+
if (i !== start && candidates[i] === candidates[i - 1]) {
43+
continue;
44+
}
45+
combo.push(candidates[i]);
46+
getCombos(target - candidates[i], i + 1);
47+
combo.pop();
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)