Skip to content

Commit 8c6a50f

Browse files
committed
combination sum solution
1 parent 8f8cd79 commit 8c6a50f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

combination-sum/hyer0705.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function combinationSum(candidates: number[], target: number): number[][] {
2+
const results: number[][] = [];
3+
4+
function backtrack(currentIndex: number, sum: number, selected: number[]) {
5+
if (sum > target) return;
6+
if (sum === target) {
7+
results.push([...selected]);
8+
return;
9+
}
10+
11+
for (let i = currentIndex; i < candidates.length; i++) {
12+
selected.push(candidates[i]);
13+
backtrack(i, sum + candidates[i], selected);
14+
selected.pop();
15+
}
16+
}
17+
18+
backtrack(0, 0, []);
19+
20+
return results;
21+
}

0 commit comments

Comments
 (0)