-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum-iv.ts
More file actions
33 lines (31 loc) · 1.09 KB
/
Copy pathcombination-sum-iv.ts
File metadata and controls
33 lines (31 loc) · 1.09 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
/**
* 377. Combination Sum IV (Medium)
* Link: https://leetcode.com/problems/combination-sum-iv/
*
* Given distinct integers `nums` and a `target`, return the number of possible
* combinations that add up to target. Different orderings count as different
* combinations (so this is really counting ordered sequences / permutations).
*
* Example:
* Input: nums = [1, 2, 3], target = 4
* Output: 7 // (1,1,1,1),(1,1,2),(1,2,1),(2,1,1),(1,3),(3,1),(2,2)
*
* Approach:
* 1-D DP counting ordered sums. dp[t] = number of ordered ways to reach t.
* dp[0] = 1 (the empty sequence). For each amount t, sum dp[t - num] over all
* nums that fit. Iterating amount in the outer loop counts orderings (unlike
* the unordered coin-change-2 layout).
*
* Time: O(target * nums.length)
* Space: O(target)
*/
export function combinationSum4(nums: number[], target: number): number {
const dp = new Array<number>(target + 1).fill(0);
dp[0] = 1;
for (let t = 1; t <= target; t++) {
for (const num of nums) {
if (num <= t) dp[t] += dp[t - num];
}
}
return dp[target];
}