Skip to content

Commit 130e582

Browse files
committed
add solution : 39. Combination Sum
1 parent b2282f5 commit 130e582

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

โ€Žcombination-sum/mmyeon.tsโ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
3+
* - ์ค‘๋ณต ํฌํ•จํ•˜์—ฌ ๋ชจ๋“  ์กฐํ•ฉ ๊ตฌํ•ด์•ผ ํ•˜๋‹ˆ๊นŒ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ํ’€๊ธฐ
4+
* - ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ํƒ์ƒ‰ํ•ด์•ผํ•˜๋Š” ํƒ€๊ฒŸ ์ค„์—ฌ๊ฐ€๋ฉด์„œ ์กฐํ•ฉ ๋งŒ๋“ค๊ธฐ
5+
* - ๋™์ผ ์กฐํ•ฉ์ถ”๊ฐ€๋˜์ง€ ์•Š๋„๋ก, startIndex ์ถ”๊ฐ€ํ•˜์—ฌ ๋‹ค์Œ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ˆœํšŒํ•˜๋„๋ก ์ œํ•œ
6+
*
7+
*
8+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n^target)
9+
* - candidates ๋ฐฐ์—ด ๊ธธ์ด n๋งŒํผ ์žฌ๊ท€๊ฐ€ ํ˜ธ์ถœ๋˜๊ณ , ๊ฐ ํ˜ธ์ถœ์€ target ๊ธธ์ด ๋งŒํผ ์ค‘์ฒฉ๋˜๋‹ˆ๊นŒ O(n^target)
10+
*
11+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(target)
12+
* - ์ตœ์•…์˜ ๊ฒฝ์šฐ target๋งŒํผ ์žฌ๊ท€ ํ˜ธ์ถœ๋˜๋‹ˆ๊นŒ O(target)
13+
*
14+
*/
15+
16+
function combinationSum(candidates: number[], target: number): number[][] {
17+
const result: number[][] = [];
18+
19+
const dfs = (target: number, combination: number[], startIndex: number) => {
20+
if (target === 0) {
21+
result.push([...combination]);
22+
return;
23+
}
24+
25+
if (target < 0) return;
26+
27+
for (let i = startIndex; i < candidates.length; i++) {
28+
combination.push(candidates[i]);
29+
dfs(target - candidates[i], combination, i);
30+
combination.pop();
31+
}
32+
};
33+
34+
dfs(target, [], 0);
35+
36+
return result;
37+
}

0 commit comments

Comments
ย (0)