-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum.ts
More file actions
44 lines (42 loc) · 1.44 KB
/
Copy pathcombination-sum.ts
File metadata and controls
44 lines (42 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 39. Combination Sum (Medium)
* Link: https://leetcode.com/problems/combination-sum/
*
* Given an array of distinct `candidates` and a `target`, return all unique
* combinations that sum to target. The same number may be chosen an unlimited
* number of times. Combinations differing only in order count as the same.
*
* Example:
* Input: candidates = [2, 3, 6, 7], target = 7
* Output: [[2, 2, 3], [7]]
*
* Approach:
* Backtracking with a `start` index to enforce non-decreasing choices (avoids
* permutations of the same combination). Because reuse is allowed we recurse
* with the same index `i`, subtracting the candidate from the remaining
* target. Prune when the remaining target goes negative.
*
* Time: O(n^(target/min)) — exponential in the worst case.
* Space: O(target/min) — recursion depth / current path.
*/
export function combinationSum(
candidates: number[],
target: number,
): number[][] {
const result: number[][] = [];
const path: number[] = [];
function backtrack(start: number, remaining: number): void {
if (remaining === 0) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) continue; // prune (works best if sorted)
path.push(candidates[i]);
backtrack(i, remaining - candidates[i]); // reuse allowed -> pass i
path.pop();
}
}
backtrack(0, target);
return result;
}