Skip to content

Commit 48e375b

Browse files
committed
solve(w03): 39. Combination Sum
1 parent 779d845 commit 48e375b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

combination-sum/jeongwoo903.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* k: 후보 수
3+
* t: target / 최소 숫자
4+
* 시간 복잡도: O(k^t)
5+
* 공간 복잡도; O(k^t * t)
6+
*/
7+
8+
/**
9+
* @param {number[]} candidates
10+
* @param {number} target
11+
* @return {number[][]}
12+
*/
13+
14+
var combinationSum = function(candidates, target) {
15+
const combine = (sum, path, startIndex) => {
16+
if (sum > target) return [];
17+
if (sum === target) return [path];
18+
19+
return candidates
20+
.slice(startIndex)
21+
.flatMap((candidate, i) =>
22+
combine(sum + candidate, [...path, candidate], startIndex + i)
23+
);
24+
};
25+
26+
return candidates.flatMap((candidate, i) =>
27+
combine(candidate, [candidate], i)
28+
);
29+
};

0 commit comments

Comments
 (0)