-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathmmyeon.ts
37 lines (31 loc) ยท 1.08 KB
/
mmyeon.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* ์ ๊ทผ ๋ฐฉ๋ฒ :
* - ์ค๋ณต ํฌํจํ์ฌ ๋ชจ๋ ์กฐํฉ ๊ตฌํด์ผ ํ๋๊น ์ฌ๊ทํจ์๋ก ํ๊ธฐ
* - ์ฌ๊ท ํธ์ถ๋ก ํ์ํด์ผํ๋ ํ๊ฒ ์ค์ฌ๊ฐ๋ฉด์ ์กฐํฉ ๋ง๋ค๊ธฐ
* - ๋์ผ ์กฐํฉ์ถ๊ฐ๋์ง ์๋๋ก, startIndex ์ถ๊ฐํ์ฌ ๋ค์ ์ธ๋ฑ์ค๋ถํฐ ์ํํ๋๋ก ์ ํ
*
*
* ์๊ฐ๋ณต์ก๋ : O(n^target)
* - candidates ๋ฐฐ์ด ๊ธธ์ด n๋งํผ ์ฌ๊ท๊ฐ ํธ์ถ๋๊ณ , ๊ฐ ํธ์ถ์ target ๊ธธ์ด ๋งํผ ์ค์ฒฉ๋๋๊น O(n^target)
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(target)
* - ์ต์
์ ๊ฒฝ์ฐ target๋งํผ ์ฌ๊ท ํธ์ถ๋๋๊น O(target)
*
*/
function combinationSum(candidates: number[], target: number): number[][] {
const result: number[][] = [];
const dfs = (target: number, combination: number[], startIndex: number) => {
if (target === 0) {
result.push([...combination]);
return;
}
if (target < 0) return;
for (let i = startIndex; i < candidates.length; i++) {
combination.push(candidates[i]);
dfs(target - candidates[i], combination, i);
combination.pop();
}
};
dfs(target, [], 0);
return result;
}