Skip to content

Commit 596a480

Browse files
committed
Combination Sum
1 parent fddee5c commit 596a480

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

combination-sum/sunjae95.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* dfs
5+
*
6+
* time complexity: O(n^k)
7+
* space complexity: O(n)
8+
*/
9+
var combinationSum = function (candidates, target) {
10+
const answer = [];
11+
12+
const dfs = (array, sum, index) => {
13+
if (sum > target) return;
14+
if (sum === target) return answer.push(array);
15+
16+
for (let i = index; i < candidates.length; i++) {
17+
const nextArray = array.concat(candidates[i]);
18+
const nextSum = sum + candidates[i];
19+
20+
dfs(nextArray, nextSum, i);
21+
}
22+
};
23+
24+
candidates.forEach((value, i) => dfs([value], value, i));
25+
26+
return answer;
27+
};

0 commit comments

Comments
 (0)