Skip to content

Commit c787f33

Browse files
committed
feat: 39. Combination Sum
1 parent 0cd8146 commit c787f33

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

combination-sum/gwbaik9717.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum = function (candidates, target) {
7+
const answer = [];
8+
const n = candidates.length;
9+
const combi = (i, sum, arr) => {
10+
for (let j = i; j < n; j++) {
11+
const candidate = candidates[j];
12+
const newSum = sum + candidate;
13+
14+
if (newSum === target) {
15+
answer.push([...arr, candidate]);
16+
continue;
17+
}
18+
19+
if (newSum > target) {
20+
continue;
21+
}
22+
23+
if (newSum < target) {
24+
combi(j, newSum, [...arr, candidate]);
25+
}
26+
}
27+
};
28+
29+
combi(0, 0, []);
30+
31+
return answer;
32+
};

0 commit comments

Comments
 (0)