Skip to content

Commit 282e74d

Browse files
committed
39 / Combination Sum / medium / 44m
1 parent 9e93cb1 commit 282e74d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

wch2208/39_Combination_Sum.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum = function (candidates, target) {
7+
const result = [];
8+
9+
const findCombinations = (remaining, current, start) => {
10+
// 종료조건
11+
if (remaining === 0) {
12+
result.push([...current]);
13+
return;
14+
}
15+
16+
if (remaining < 0) return;
17+
18+
// 현재 단계에서 할 일
19+
for (let i = start; i < candidates.length; i++) {
20+
// 1. 현재 숫자를 선택
21+
current.push(candidates[i]);
22+
23+
// 2. 이 숫자를 선택한 상태에서 재귀 호출
24+
findCombinations(remaining - candidates[i], current, i);
25+
26+
// 3. 백트래킹: 현재 숫자를 제거하고 다른 가능성 시도
27+
current.pop();
28+
}
29+
};
30+
31+
findCombinations(target, [], 0);
32+
33+
return result;
34+
};
35+
36+
// time: 44m

0 commit comments

Comments
 (0)