Skip to content

Commit 8b91fc3

Browse files
Jaehyeon Robert HanJaehyeon Robert Han
authored andcommitted
combination-sum solution
1 parent 205f7a9 commit 8b91fc3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

combination-sum/Zioq.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum = function(candidates, target) {
7+
let result = [];
8+
9+
function find_combination(index, target, current) {
10+
if (target === 0) {
11+
result.push([...current]);
12+
return;
13+
}
14+
15+
for (let i = index; i < candidates.length; i++) {
16+
// Only proceed if current number doesn't exceed target
17+
if (candidates[i] <= target) {
18+
// Include current number in combination
19+
current.push(candidates[i]);
20+
21+
// Recursive call with:
22+
// - same index i (allowing reuse of same number)
23+
// - reduced target by current number
24+
find_combination(i, target - candidates[i], current);
25+
26+
// Backtrack: remove the last added number to try other combinations
27+
current.pop();
28+
}
29+
}
30+
}
31+
32+
find_combination(0, target, []);
33+
return result;
34+
};
35+
36+
/*
37+
38+
39+
40+
*/
41+
42+
console.log(combinationSum([2,3,6,7], 7))
43+
44+

0 commit comments

Comments
 (0)