Skip to content

Commit c341117

Browse files
committed
add Combination Sum solution
1 parent f29b91f commit c341117

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

combination-sum/HoonDongKang.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* [Problem]: [39] Combination Sum
3+
*
4+
* (https://leetcode.com/problems/combination-sum/description/)
5+
*/
6+
function combinationSum(candidates: number[], target: number): number[][] {
7+
// 시간복잡도: O(c^t)
8+
// 공간복잡도 O(t)
9+
function dfsFunc(candidates: number[], target: number): number[][] {
10+
let result: number[][] = [];
11+
let nums: number[] = [];
12+
13+
function dfs(start: number, total: number): void | number[][] {
14+
if (total > target) return;
15+
if (total === target) {
16+
result.push([...nums]);
17+
return result;
18+
}
19+
for (let i = start; i < candidates.length; i++) {
20+
let num = candidates[i];
21+
nums.push(num);
22+
dfs(i, total + num);
23+
nums.pop();
24+
}
25+
}
26+
27+
dfs(0, 0);
28+
return result;
29+
}
30+
31+
// 시간복잡도: O(c*t)
32+
// 공간복잡도 O(c*t)
33+
function dpFunc(candidates: number[], target: number): number[][] {
34+
const dp: number[][][] = Array(target + 1)
35+
.fill(null)
36+
.map(() => []);
37+
38+
dp[0] = [[]];
39+
40+
for (const num of candidates) {
41+
for (let t = num; t <= target; t++) {
42+
for (const comb of dp[t - num]) {
43+
dp[t].push([...comb, num]);
44+
}
45+
}
46+
}
47+
48+
return dp[target];
49+
}
50+
51+
return dpFunc(candidates, target);
52+
}
53+
54+
console.log(combinationSum([2, 3, 6, 7], 7));

0 commit comments

Comments
 (0)