Count the ordered sequences of available positive values that add to an exact target.
Problem
Input. A list nums of distinct positive integers and a nonnegative integer target.
Output. Return the number of ordered value sequences whose sum equals target.
Rules. A value may be reused any number of times; different orders count separately. Target zero has one sequence: the empty sequence. An unreachable positive target has zero sequences. Leave the input unchanged. The reference neither validates positivity nor removes duplicate input values.
Example. For nums = [1, 2] and target = 3, return 3.
The sequences are [1, 1, 1], [1, 2], and [2, 1].
Picture
For values [1,2,3] and target four:
| Final value | Prefix total | Prefix count | Example |
|---|---|---|---|
| 1 | 3 | 4 | [3,1] |
| 2 | 2 | 2 | [2,2] |
| 3 | 1 | 1 | [1,3] |
The result is . [1,3] and [3,1] belong to different groups and are different sequences.
Reuse the disjoint predecessor-count rule.
The base ways[0]=1 counts one empty sequence. It lets a final value form a one-element sequence without a special case.
Before processing total, every smaller total is final.
The update adds ways[total-num] for each allowed final value. Positive values make every dependency smaller; distinct values prevent counting a final group twice.
Keep totals outside choices so every ordered prefix is available. Combination Sum instead treats reordered values as one answer. For this example, unordered counting gives four, not seven.
Nodes below show total:ways. Each lower node contributes its count for the labeled final value.
Target zero returns one, including when values are empty. Positive targets with no values return zero. Zero creates self-dependence; negative values can index future or nonexistent slots. Neither belongs in this recurrence unchanged.
Problem trace
Separate fixture: count ordered sequences with the code's full move set
- base
- 0
- indices
- total 0..4
- index 0
- 1
- total 1
- not shown→1
- base
- 0→not shown
- recurrence
- not shown→end 1 -> ways[0] = 1
- total 2
- 1→2
- recurrence
- end 1 -> ways[0] = 1→ways[1] + ways[0] = 1 + 1 = 2
- sequences
- [1]→[1,1], [2]
- total 3
- 2→3
- recurrence
- ways[1] + ways[0] = 1 + 1 = 2→ways[2] + ways[1] + ways[0] = 2 + 1 + 1 = 4
- sequences
- [1,1], [2]→not shown
- total 4
- 3→4
- recurrence
- ways[2] + ways[1] + ways[0] = 2 + 1 + 1 = 4→ways[3] + ways[2] + ways[1] = 4 + 2 + 1 = 7
- result
- not shown→7
- Recognize it
- Use it when order matters, values may be reused, and every sequence reaching a total has one unambiguous final value that reduces it to a smaller solved total.
- Keep true
- Before processing total t, ways[0..t-1] contain exact ordered-sequence counts; after trying every num <= t, ways[t] counts each sequence exactly once by its final number.
- Reuse it
- To count ordered constructions, partition answers by the last decision and iterate states before choices; changing loop order can change the combinatorial object being counted.
Reference drawing
Problem trace
Group ordered sequences by their last number, then add their counts
Execution trace
- base
- 0
- indices
- total 0..4
- index 0
- 1
- total 1
- not shown→1
- base
- 0→not shown
- recurrence
- not shown→end 1 -> ways[0] = 1
- total 2
- 1→2
- recurrence
- end 1 -> ways[0] = 1→ways[1] + ways[0] = 1 + 1 = 2
- sequences
- [1]→[1,1], [2]
- total 3
- 2→3
- recurrence
- ways[1] + ways[0] = 1 + 1 = 2→ways[2] + ways[1] + ways[0] = 2 + 1 + 1 = 4
- sequences
- [1,1], [2]→not shown
- total 4
- 3→4
- recurrence
- ways[2] + ways[1] + ways[0] = 2 + 1 + 1 = 4→ways[3] + ways[2] + ways[1] = 4 + 2 + 1 = 7
- result
- not shown→7
- Recognize it
- Use it when order matters, values may be reused, and every sequence reaching a total has one unambiguous final value that reduces it to a smaller solved total.
- Keep true
- Before processing total t, ways[0..t-1] contain exact ordered-sequence counts; after trying every num <= t, ways[t] counts each sequence exactly once by its final number.
- Reuse it
- To count ordered constructions, partition answers by the last decision and iterate states before choices; changing loop order can change the combinatorial object being counted.
Code
def combination_sum_four(nums: list[int], target: int) -> int:
ways = [1] + [0] * target
for total in range(1, target + 1):
for num in nums:
if num <= total:
ways[total] += ways[total - num]
return ways[target]
Cost: time and space.
This counts additions and integer slots, not fixed-width machine operations. Exact sequence counts can require growing bit widths.
Change Order Equivalence or Bound Length
Start from combination_sum_four. Each adaptation changes the counted object or the reason its dependencies terminate.
-
Ignore value order.
New task: Count unordered reusable-value combinations for a nonnegative target.
Picture and change: Process denominations outside ascending totals. After each denomination, counts use only values processed so far. Deduplicate numeric values and reject nonpositive ones.
Code: Complete replacement:
def unordered_combinations(nums, target): values = sorted(set(nums)) if any(value <= 0 for value in values): raise ValueError("positive values required") ways = [1] + [0] * target for value in values: for total in range(value, target + 1): ways[total] += ways[total - value] return ways[target]Check:
[1,2,3], target four gives four. The source gives seven. This changes the answer, not just runtime.Use when: Permuting values should not create a new answer. After preprocessing unique values, the DP uses additions and slots.
-
Bound length before allowing arbitrary integers.
New task: Count ordered numeric-value sequences of at most a nonnegative integer
max_length, including the empty sequence.Picture and change: Keep a separate sum-count map for each exact length. The length bound replaces positive-sum decrease as the termination argument.
Code: Complete replacement, deduplicating numeric values:
def bounded_sequence_count(nums, target, max_length): values = sorted(set(nums)) counts, answer = {0: 1}, int(target == 0) for _ in range(max_length): next_counts = {} for total, count in counts.items(): for value in values: next_counts[total + value] = next_counts.get(total + value, 0) + count counts = next_counts answer += counts.get(target, 0) return answerCheck:
[0,1], target one, length at most two gives[1],[0,1],[1,0]: three sequences. For[-1,1], target zero, the same bound counts empty,[-1,1]and[1,-1].Use when: A finite resource bound permits nonpositive values. Without it, zero-sum insertions can give infinitely many sequences. If sums occur at length , processing length bound takes work beyond preprocessing. Maps use slots; exact-integer costs also grow with bit width.
Rebuild Disjointness
Why do duplicate input values break the source’s final-value partition?
Answer: The loop adds the same numeric final group repeatedly. Deduplicate unless candidate identities intentionally define different choices.