SDE & MLE Prep

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]