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)