sagelearnai

Combination Sum IV

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #377

Given distinct positive nums, return the number of ordered sequences (order matters, so (1,2) and (2,1) are different) that sum to target. Numbers may be reused.

Examples

text
nums = [1,2,3], target = 4  →  7
  (1,1,1,1) (1,1,2) (1,2,1) (2,1,1) (1,3) (3,1) (2,2)
nums = [9], target = 3      →  0

Hints

  1. Condition on the last number of the sequence: dp[t] = Σ dp[t − x] over x in nums.
  2. Compare with Coin Change II (unordered combinations). There, the coin loop is outside. Here the target loop is outside.

Approach

dp[0] = 1 (the empty sequence). For t from 1 to target: dp[t] = Σ_{x ≤ t} dp[t − x].

Loop order is everything:

  • for t: for x: counts permutations. Every last element is tried at every total.
  • for x: for t: counts combinations. The coins are used in a fixed order (Coin Change II).

This distinction is one of the most common DP interview traps.

Complexity

Time: O(target · n). Space: O(target).

Python solution
def combinationSum4(nums, target):
    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]
JavaScript solution
function combinationSum4(nums, target) {
  const dp = new Array(target + 1).fill(0);
  dp[0] = 1;
  for (let t = 1; t <= target; t++) for (const x of nums) if (x <= t) dp[t] += dp[t - x];
  return dp[target];
}