-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathZioq.js
44 lines (32 loc) · 1.1 KB
/
Zioq.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
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
let result = [];
function find_combination(index, target, current) {
if (target === 0) {
result.push([...current]);
return;
}
for (let i = index; i < candidates.length; i++) {
// Only proceed if current number doesn't exceed target
if (candidates[i] <= target) {
// Include current number in combination
current.push(candidates[i]);
// Recursive call with:
// - same index i (allowing reuse of same number)
// - reduced target by current number
find_combination(i, target - candidates[i], current);
// Backtrack: remove the last added number to try other combinations
current.pop();
}
}
}
find_combination(0, target, []);
return result;
};
/*
*/
console.log(combinationSum([2,3,6,7], 7))