Skip to content

Commit 6cad65f

Browse files
committed
solve: combination sum
1 parent fe8e8bf commit 6cad65f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

combination-sum/reach0908.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 시간복잡도 O(n^(T/m))
3+
* 풀이방법: DFS 백트래킹
4+
* 결과: 2ms
5+
* @param {number[]} candidates
6+
* @param {number} target
7+
* @return {number[][]}
8+
*/
9+
const combinationSum = function (candidates, target) {
10+
const result = [];
11+
const nums = [];
12+
13+
const sortedCandidates = candidates.sort((a, b) => a - b);
14+
15+
function dfs(start, sum) {
16+
if (sum === target) {
17+
result.push([...nums]);
18+
}
19+
20+
for (let i = start; i < sortedCandidates.length; i += 1) {
21+
const num = sortedCandidates[i];
22+
23+
if (sum + num > target) break;
24+
25+
nums.push(num);
26+
dfs(i, sum + num);
27+
nums.pop();
28+
}
29+
}
30+
31+
dfs(0, 0);
32+
33+
return result;
34+
};

0 commit comments

Comments
 (0)