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.
Read it this way: For nums = [1,2,3] and target = 4, ways[0] = 1 represents choosing nothing; all positive totals start at 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Counting DP.
Simple idea: To build total, place each possible value last. Add the number of ordered
ways to build total - value. Start with one way to build zero: choose nothing.
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]