Skip to content

Commit 8449524

Browse files
authored
combination sum solution
1 parent cfb7db6 commit 8449524

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

combination-sum/yhkee0404.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function combinationSum(candidates: number[], target: number, dp = new Map()): number[][] {
2+
if (target <= 0) {
3+
return [];
4+
}
5+
let ans = dp.get(target);
6+
if (ans !== undefined) {
7+
return ans;
8+
}
9+
ans = [];
10+
for (const candidate of candidates) {
11+
if (target == candidate) {
12+
ans.push([candidate]);
13+
continue;
14+
}
15+
for (const combination of combinationSum(candidates, target - candidate, dp)) {
16+
if (combination[combination.length - 1] > candidate) {
17+
continue;
18+
}
19+
ans.push([...combination, candidate]);
20+
}
21+
}
22+
dp.set(target, ans);
23+
return ans;
24+
};

0 commit comments

Comments
 (0)