Skip to content

Commit 9e5e459

Browse files
committed
combination-sum
1 parent 306fe90 commit 9e5e459

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

combination-sum/taewanseoul.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 39. Combination Sum
3+
* Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
4+
* The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
5+
* The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
6+
*
7+
* https://leetcode.com/problems/combination-sum/description/
8+
*/
9+
10+
// O(n^m) time
11+
// O(n) space
12+
function combinationSum(candidates: number[], target: number): number[][] {
13+
const res: number[][] = [];
14+
dfs(candidates, 0, target, [], res);
15+
return res;
16+
}
17+
18+
function dfs(
19+
nums: number[],
20+
start: number,
21+
remaining: number,
22+
path: number[],
23+
res: number[][]
24+
) {
25+
if (remaining === 0) {
26+
res.push([...path]);
27+
return;
28+
}
29+
30+
for (let i = start; i < nums.length; i++) {
31+
const num = nums[i];
32+
if (remaining - num < 0) continue;
33+
path.push(num);
34+
dfs(nums, i, remaining - num, path, res);
35+
path.pop();
36+
}
37+
}

0 commit comments

Comments
 (0)