Skip to content

Commit 2bf8e97

Browse files
committed
feat(soobing): week3 > combination-sum
1 parent 94e3f50 commit 2bf8e97

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

combination-sum/soobing2.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 문제 유형
3+
* - DP: DFS + Backtracking
4+
*
5+
* 문제 설명
6+
* - 주어진 숫자 배열에서 조합을 만들어서 합이 target이 되는 경우를 찾기
7+
*
8+
* 아이디어
9+
* 1) Backtracking 활용
10+
* - dfs를 통해 합이 target이 되는 모든 케이스를 탐색한다. (단, 조건 체크 후에 즉시 중단 = 백트래킹)
11+
*/
12+
function combinationSum(candidates: number[], target: number): number[][] {
13+
const result: number[][] = [];
14+
15+
function backtracking(
16+
startIndex: number,
17+
combination: number[],
18+
total: number
19+
) {
20+
if (total === target) {
21+
result.push([...combination]);
22+
return;
23+
}
24+
25+
if (total > target) return;
26+
27+
for (let i = startIndex; i < candidates.length; i++) {
28+
combination.push(candidates[i]);
29+
backtracking(i, combination, total + candidates[i]);
30+
combination.pop();
31+
}
32+
}
33+
34+
backtracking(0, [], 0);
35+
return result;
36+
}

0 commit comments

Comments
 (0)