377. Combination Sum IV
Problem
Count the sequences of values from nums (distinct positive integers, reusable) that add up to target. Different orders count as different sequences.
Example: nums = [1,2,3], target = 4 → 7
Constraints: the answer fits in 32 bits.
Order matters (sequences) → outer loop over target, inner over nums: dp[t] += dp[t − x]. (Swapping the loops counts combinations instead — that's 518.)
Complexity: O(target × n).
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [1] + [0] * target
for t in range(1, target + 1):
for x in nums:
if x <= t:
dp[t] += dp[t - x]
return dp[target]
assert Solution().combinationSum4([1, 2, 3], 4) == 7
assert Solution().combinationSum4([9], 3) == 0
class Solution {
public int combinationSum4(int[] nums, int target) {
// the answer fits in int, but unused intermediate states can overflow -> keep them mod 2^31-1
long[] dp = new long[target + 1];
dp[0] = 1;
for (int t = 1; t <= target; t++)
for (int x : nums) if (x <= t) dp[t] = (dp[t] + dp[t - x]) % Integer.MAX_VALUE;
return (int) dp[target];
}
}
func combinationSum4(nums []int, target int) int {
dp := make([]int, target+1) // dp[t] = ordered ways to sum to t
dp[0] = 1
for t := 1; t <= target; t++ {
for _, x := range nums { // the last number of the sequence
if x <= t {
dp[t] += dp[t-x]
}
}
}
return dp[target]
}