TRT
Sign in
mediumAdvancedLeetCode#counting DP#loop order

Combination sum IV

Count the ordered sequences of numbers that sum to a target, and see how the loop order decides whether orderings are counted.

The Runtime Theory Team1 min read
Taught inKnapsack and subsetsPro — members onlyChoosing a subset of items under a capacity is solved with a table over items and capacities. Whether each item can be used once or many times comes down to the direction of one loop.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 2, 3], target = 4

out7

innums = [9], target = 3

out0

innums = [1, 2], target = 3

out3

Given distinct positive numbers, count the sequences (order matters) of them, with repetition, that sum to target.

Before you code

Despite the name, this counts orderings: 1 + 2 and 2 + 1 are different. That is decided entirely by which loop is outside.

Hints

  1. dp[0] = 1.
  2. Loop over totals t from 1 to target on the outside, and numbers on the inside: dp[t] += dp[t - x].
  3. Swap the loops (numbers outside) and you count combinations instead, as in Coin change II.

Production & complexity notes

When solving Combination sum IV on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Knapsack and subsets to reinforce the underlying pattern.

What it practices

Loop order in counting knapsacks, from Knapsack and subsets.

Not started

Sign in to save your learning progress.

Sign in to save