{"id":"combination-sum-iv","title":"Combination Sum IV","difficulty":"medium","patterns":["dp-knapsack"],"primaryConcept":"dp-knapsack-counting","concepts":["dp-knapsack-counting"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","sizeMetric":"target","constraints":["positive","distinct"],"valueRange":{"min":1,"max":20},"secondaryParams":{"target":{"strategy":"random-int","value":{"min":0,"max":40}}}},"description":"Given an array of distinct positive integers `nums` and an integer `target`, return the number of ordered combinations that add up to `target`.\n\nDifferent orders count as different combinations. For example, `[1, 2]` and `[2, 1]` are two different combinations.","examples":[{"input":"nums = [1,2,3], target = 4","output":"7","explanation":"The ordered combinations are 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 1+3, and 3+1."},{"input":"nums = [9], target = 3","output":"0","explanation":"The only number is larger than the target."}],"constraints":[{"id":"1-len-nums-200","text":"1 <= len(nums) <= 200","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":200}},{"id":"1-nums-i-1000","text":"1 <= nums[i] <= 1000","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":1,"max":1000}},{"id":"all-values-in-nums-are-distinct","text":"All values in nums are distinct","check":{"kind":"uniqueness","target":"nums","selector":"items"}},{"id":"0-target-1000","text":"0 <= target <= 1000","check":{"kind":"valueRange","target":"target","selector":"value","min":0,"max":1000}},{"id":"the-answer-is-guaranteed-to-fit-in-a-32-bit-signed-integer","text":"The answer is guaranteed to fit in a 32-bit signed integer","check":{"kind":"guarantee","guarantee":"resultRange","min":-2147483648,"max":2147483647}}],"starterCode":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        # Your code here\n        pass","functionName":"combinationSum4","testCases":[{"id":"1","input":{"nums":[1,2,3],"target":4},"expected":7,"description":"Canonical sample with multiple orderings."},{"id":"2","input":{"nums":[9],"target":3},"expected":0,"description":"No candidate can fit."},{"id":"3","input":{"nums":[1],"target":0},"expected":1,"description":"The empty ordered combination makes sum zero."},{"id":"4","input":{"nums":[1,2],"target":3},"expected":3,"description":"1+1+1, 1+2, and 2+1."},{"id":"5","input":{"nums":[2,4,6],"target":8},"expected":7,"description":"Even choices with several ordered decompositions."},{"id":"6","input":{"nums":[3,4,5],"target":9},"expected":3,"description":"3+3+3, 4+5, and 5+4."},{"id":"7","input":{"nums":[2,5,10],"target":1},"expected":0,"description":"Every candidate is larger than the target."},{"id":"h1","input":{"nums":[1,2,3],"target":5},"description":"A small target with many orderings.","expected":13},{"id":"h2","input":{"nums":[2,3,5],"target":8},"description":"Multiple ordered combinations without a 1-valued step.","expected":6},{"id":"h3","input":{"nums":[4,5,6],"target":9},"description":"Only one two-number composition is possible.","expected":2},{"id":"h4","input":{"nums":[1,3,4],"target":6},"description":"The empty ordered sequence is the only way to reach target zero.","expected":9},{"id":"h5","input":{"nums":[2,4,6],"target":6},"description":"Ordered compositions count two-number permutations separately.","expected":4}],"hints":[{"level":1,"content":"Let `dp[total]` mean the number of ordered combinations that sum to `total`."},{"level":2,"content":"For each total, try each number as the final choice in the ordered combination."},{"level":3,"content":"If `num <= total`, then every ordered combination for `total - num` can be extended by appending `num`."}],"guidedFlow":{"version":2,"progressRevision":"combination-sum-iv-2026-07-19-reused-subtotal-counts","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Choose the approach whose state and complexity match the constraints.","approaches":[{"id":"brute-force-recursion","name":"Enumerate every ordered sequence","summary":"Recursively append a number, then solve the smaller remaining subtotal, listing every sequence to the target.","decisionReason":"Every distinct order is a separate path, so the count of paths explodes and the same remaining subtotal is re-solved on each one.","complexity":{"time":"Exponential","space":"O(target)"},"tradeoffs":["Runs in exponential time and uses O(target) recursion space."],"isOptimal":false,"steps":["Append one number to the current sequence","Recurse on the remaining subtotal","Count a finished sequence when the remainder hits zero"]},{"id":"bottom-up-counting-dp","name":"Bottom-up ordered-count table","summary":"Store, for each subtotal, the number of ordered sequences that reach it, and read each one through every possible final number.","decisionReason":"This is the intended approach: it counts each subtotal once and reuses it, matching the target complexity while keeping the state explicit.","complexity":{"time":"O(target * n)","space":"O(target)"},"tradeoffs":["Runs in O(target * n) time and uses O(target) space."],"isOptimal":true,"steps":["Seed subtotal 0 with the one empty sequence","Sweep subtotals upward","For each subtotal, add the counts of every reduced subtotal"]}]},"codingCheckpoints":[{"id":"init-dp-array","title":"Initialize the count table","description":"Create a table for every subtotal from 0 through target and seed one way to reach subtotal 0.","commonMistakes":["Leaving the zero subtotal at 0","Sizing the table to target instead of target + 1"],"hint":"There is exactly one ordered sequence that sums to 0: the empty one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_count_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Allocate the counting table over subtotals and seed the zero subtotal with one empty ordered sequence.","doneWhen":"This step is done when the table covers target + 1 cells, every count starts at zero, and the zero subtotal is set to one before any transition runs.","shouldFailWhen":"This step should fail if the table is the wrong size, the zero base count is missing, or non-base cells start as prefilled answers.","roles":["count table over subtotals","zero subtotal base case","ordered-sequence count"],"mustProve":["The count table has one cell for each subtotal from 0 through target.","The zero subtotal is seeded with exactly one way before the transitions run."],"mustNotAccept":["A scalar counter with no per-subtotal state.","A table that seeds every subtotal to one."],"equivalentVariants":["Use a list, array, or vector of zero counts with length target + 1.","Seed the zero index to one before the loops."],"proofSnippets":[{"id":"py-combination-sum-iv-init-dp-array","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        return 0"}]}},{"id":"outer-loop","title":"Sweep every subtotal in increasing order","description":"Visit each subtotal from 1 through target as the outer loop, so every subtotal is settled before larger ones read it.","commonMistakes":["Looping numbers first, which counts each multiset once instead of each order","Stopping before the target subtotal"],"hint":"Each subtotal must gather ways from every possible final number, so the subtotal is the outer axis.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Drive the transition by visiting every subtotal from one through target in an outer pass.","doneWhen":"This step is done when the code scans subtotal values from one to target around the candidate-number loop.","shouldFailWhen":"This step should fail if there is no subtotal scan, or the loops nest so that each multiset is counted once instead of each ordering.","roles":["subtotal index","target boundary","outer state-space scan"],"mustProve":["The loop visits the subtotal cells in the table.","The subtotal scan wraps the candidate-number choice."],"mustNotAccept":["Only looping over input numbers without a subtotal scan.","A combination-counting loop order that fixes one number order."],"equivalentVariants":["Use range(1, target + 1) or an equivalent inclusive subtotal loop."],"proofSnippets":[{"id":"py-combination-sum-iv-outer-loop","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            pass\n        return 0"}]}},{"id":"inner-loop","title":"Try each number as the final step","description":"For the current subtotal, scan every number in nums as a possible last number of the ordered sequence.","commonMistakes":["Trying only one number","Breaking out before every candidate is tried"],"hint":"Any number can be the last step of an ordered sequence, as long as it fits inside the subtotal.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Nest a scan over candidate numbers inside the subtotal scan so each subtotal can absorb every possible final number.","doneWhen":"This step is done when each subtotal iteration considers the numbers in nums as the final choice.","shouldFailWhen":"This step should fail if the code never scans the candidate numbers inside the subtotal loop.","roles":["candidate number","nested choice scan","current subtotal"],"mustProve":["The code has a nested scan over candidate numbers inside the subtotal loop."],"mustNotAccept":["Hard-coding one candidate.","Using only the first number."],"equivalentVariants":["Loop directly over the values or over indices into nums."],"proofSnippets":[{"id":"py-combination-sum-iv-inner-loop","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                pass\n        return 0"}]}},{"id":"dp-update","title":"Add the ways from the reduced subtotal","description":"When a number fits inside the subtotal, add the count from total minus that number into the current subtotal.","commonMistakes":["Replacing the count instead of adding to it","Reading the wrong predecessor subtotal"],"hint":"Every ordered sequence for total minus num becomes one for total by appending num as the final step.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"applies_additive_subset_transition","scope":"dp-update","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Apply the additive count recurrence from the reduced subtotal into the current subtotal when the number fits.","doneWhen":"This step is done when the code guards on whether the number fits and adds the count at total minus the number into the current subtotal.","shouldFailWhen":"This step should fail if the update overwrites instead of adds, reads the wrong predecessor, or stores a boolean instead of a count.","roles":["current subtotal count","candidate number","reduced subtotal count","additive recurrence"],"mustProve":["The transition is guarded by whether the candidate number fits inside the subtotal.","The update adds the reduced subtotal count into the current subtotal count."],"mustNotAccept":["Assigning a boolean reachable flag instead of a count.","Updating the current subtotal from itself."],"equivalentVariants":["Use dp[total] += dp[total - num].","Use dp[total] = dp[total] + dp[total - num]."],"proofSnippets":[{"id":"py-combination-sum-iv-dp-update","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                if num <= total:\n                    dp[total] += dp[total - num]\n        return 0"}]}},{"id":"return-result","title":"Return the target count","description":"Return the number of ordered sequences stored at the target subtotal.","commonMistakes":["Returning the whole table","Returning the last candidate count instead of the target cell"],"hint":"The target cell holds every ordered sequence that sums to target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal count stored at the target subtotal.","doneWhen":"This step is done when the function returns the table cell at the target index after every subtotal is filled.","shouldFailWhen":"This step should fail if the code returns a scalar loop variable, the wrong index, or the full table.","roles":["target subtotal","terminal table cell","final answer"],"mustProve":["The returned value reads the table at the target index."],"mustNotAccept":["Returning the entire table.","Returning the zero subtotal."],"equivalentVariants":["Return the target-indexed cell from the one-dimensional table."],"proofSnippets":[{"id":"py-combination-sum-iv-return-result","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                if num <= total:\n                    dp[total] += dp[total - num]\n        return dp[target]"}]}}],"slides":[{"id":"read-the-signal","chapter":"Counting orders","kind":"info","eyebrow":"Read the problem","title":"Count the ordered sequences that hit the target","workspacePanel":"problem","body":["You get distinct positive numbers and a target. Count how many ordered sequences of those numbers, reusing any number freely, add up to exactly the target.","The safe first move is to spell out every sequence by appending one number at a time. Watch what that costs."]},{"id":"brute-force","chapter":"Counting orders","kind":"code-trace","eyebrow":"The obvious way","title":"Append a number, then solve the rest","summary":"Trying every number as the next step does reach the target down each path, but the same remaining subtotals keep getting re-solved. Watch how fast the branching grows.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def count(remaining: int, nums: list[int]) -> int:\n    if remaining == 0:\n        return 1\n    ways = 0\n    for num in nums:\n        if num <= remaining:\n            ways += count(remaining - num, nums)\n    return ways","steps":[{"id":"fork","title":"Remaining 3 forks by final number","codeLine":5,"summary":"Take just the numbers 1 and 2 for a moment. Remaining 3 appends a 1 and solves 2, or appends a 2 and solves 1. Each branch keeps appending until it hits 0.","state":{"tree":[3,2,1,1,0,0,null,0],"node":0}},{"id":"re-solve","title":"Remaining 1 is solved more than once","codeLine":6,"summary":"Remaining 1 turns up on two branches: directly under remaining 3, and again under the remaining 2 below it. Each one is solved from scratch, since nothing remembers the count.","state":{"tree":[3,2,1,1,0,0,null,0],"node":2,"swapped":[3]}},{"id":"count-leaves","title":"It returns 3 for remaining 3","codeLine":8,"summary":"The three branches that reach 0 are the sequences 1+1+1, 1+2, and 2+1. Correct here, but the branching re-walks shared subtotals at every level.","state":{"tree":[3,2,1,1,0,0,null,0],"visited":[4,5,7],"node":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (remaining === 0) {\n    return 1;\n}\nlet ways = 0;\nfor (const num of nums) {\n    if (num <= remaining) {\n        ways += count((remaining - num), nums);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (remaining === 0) {\n    return 1;\n}\nlet ways = 0;\nfor (const num of nums) {\n    if (num <= remaining) {\n        ways += count((remaining - num), nums);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (remaining == 0) {\n    return 1;\n}\nint ways = 0;\nforeach (int num in nums) {\n    if (num <= remaining) {\n        ways += Count(remaining - num, nums);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (remaining == 0) {\n    return 1;\n}\nint ways = 0;\nfor (int num : nums) {\n    if (num <= remaining) {\n        ways += count((remaining - num), nums);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (remaining == 0) {\n    return 1;\n}\nint ways = 0;\nfor (Integer num : nums) {\n    if (num <= remaining) {\n        ways += count((remaining - num), nums);\n    }\n}\nreturn ways;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":7,"endLine":9}}}}},"body":["For a remaining subtotal, try each number as the next step and add up the ways to finish the rest. The tree shows that recursion on the numbers 1 and 2, where the repeat is easy to see."]},{"id":"repeated-work-probe","chapter":"Counting orders","kind":"case-probe","eyebrow":"Name the waste","title":"As the target grows, how does this cost grow?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-work-state","state":{"tree":[3,2,1,1,0,0,null,0],"node":2,"swapped":[3]}}]},"summary":"Both highlighted nodes are remaining 1: the branch that appends 2 first, and the branch that appends 1 then 1. Each is solved from scratch.","options":[{"id":"exponential-resolve","label":"The branches multiply, and a handful of remaining subtotals are re-solved on every one","rationale":"Each step forks into one branch per fitting number, so the call tree roughly triples in size each time the target climbs by a step, yet only subtotals 0 through target ever appear, so the same few are re-solved across exponentially many branches.","isCorrect":true},{"id":"linear-once","label":"It grows steadily, since each remaining subtotal is solved once on the way down","rationale":"Nothing remembers a subtotal once solved, so remaining 1 is re-derived on every branch that lands on it; the work is not solved once, it is repeated per branch.","isCorrect":false},{"id":"sum-cost","label":"It grows with the size of the additions, since longer sequences sum more numbers","rationale":"Each addition is one cheap operation. The blowup comes from many branches re-solving the same remaining subtotals.","isCorrect":false}],"answer":"The branches grow exponentially with the target, while only the subtotals 0 through target ever recur. The same small set of subproblems is being solved on countless branches."},{"id":"reuse-subtotal-result","chapter":"Counting orders","kind":"case-probe","eyebrow":"Reuse the repeated answer","title":"Two branches arrive at remaining 1. What result can they safely share?","workspacePanel":"visualizer","summary":"From remaining 1, the future choices no longer depend on how the branch arrived there. Both calls ask the same question about the same remaining amount.","options":[{"id":"completion-count","label":"The number of ordered completions from remaining 1","rationale":"Every call with the same remaining amount has the same possible suffixes. Compute that completion count once, then let every branch reuse it.","isCorrect":true},{"id":"whole-prefix","label":"The exact prefix that led to remaining 1","rationale":"The prefixes differ, which is precisely why they cannot be the shared state. Their future work is identical even though their past paths are not."},{"id":"one-global-count","label":"One global count for every remaining amount","rationale":"Different remaining amounts have different completion counts. The reusable result must be keyed by the subtotal being solved."}],"answer":"Share the completion count for remaining 1. More generally, remember one count for each subtotal from 0 through target; any later branch that reaches the same subtotal can read that result instead of rebuilding its subtree.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reuse-subtotal-state","state":{"tree":[3,2,1,1,0,0,null,0],"node":2,"swapped":[3]}}]}},{"id":"state-bridge","chapter":"The rule","kind":"info","eyebrow":"Store the work","title":"Give every subtotal one cell to remember","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-bridge-state","state":{"nums":[1,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"body":["The recursion kept re-solving the same remaining subtotals because nothing held on to an answer once it was found. The fix is one cell per subtotal, filled once and read back.","Here is that table for target 4, still blank above subtotal 0. Before any cell can be filled, the next job is to pin down what a single cell is supposed to count."]},{"id":"state-meaning","chapter":"The rule","kind":"case-probe","eyebrow":"Set up the state","title":"What should each table cell count?","summary":"A table cell per subtotal is only useful once its meaning is pinned down.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-state","state":{"nums":[1,1,2,0,0],"i":3,"labels":{"nums":"dp","i":"total"}}}]},"options":[{"id":"ordered-count","label":"The number of ordered sequences that sum to that subtotal","rationale":"A larger subtotal is reached by appending one final number to a smaller subtotal, so a count of ordered sequences per subtotal is what the next subtotal reads.","isCorrect":true},{"id":"unordered-count","label":"The number of multisets that sum to that subtotal","rationale":"Multisets ignore order, but 1+2 and 2+1 must count separately here. Counting multisets would answer a different problem.","isCorrect":false},{"id":"min-numbers","label":"The fewest numbers needed to reach that subtotal","rationale":"A minimum length throws away the count of ways. The task is how many sequences reach the subtotal, not how short one is.","isCorrect":false}],"answer":"Each cell holds the number of ordered sequences that sum to that subtotal, so the next subtotal can extend them by one final number."},{"id":"recurrence","chapter":"The rule","kind":"case-probe","eyebrow":"Build the rule","title":"Where do the ways for a subtotal come from?","summary":"Subtotal 4 is being filled. Subtotals 0 through 3 already hold their counts: 1, 1, 2, 4.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recurrence-state","state":{"nums":[1,1,2,4,0],"i":4,"labels":{"nums":"dp","i":"total"}}}]},"options":[{"id":"sum-reduced","label":"For each number that fits, the count at the subtotal that many steps behind","rationale":"Fixing the final number splits the sequences by their last step: appending 1, 2, or 3 to subtotals 3, 2, and 1 gives 4 + 2 + 1 = 7, every order kept distinct.","isCorrect":true},{"id":"prev-cell-only","label":"Just the count at the subtotal one step behind","rationale":"That only counts sequences ending in 1. Sequences ending in 2 or 3 reach subtotal 4 from subtotals 2 and 1 and would be missed.","isCorrect":false},{"id":"one-per-number","label":"One way for each number that fits inside the subtotal","rationale":"That counts final numbers, not sequences. Each final number extends every ordered way to the reduced subtotal, so the reduced counts must be added.","isCorrect":false}],"answer":"For every number that fits, add the count at total minus that number: dp[4] = dp[3] + dp[2] + dp[1] = 4 + 2 + 1 = 7, splitting the sequences by their final number."},{"id":"base-case","chapter":"The rule","kind":"case-probe","eyebrow":"Set the floor","title":"Before any subtotal is filled, what should subtotal 0 hold?","summary":"Every transition reads total minus a number, so a number landing exactly on its subtotal reads from subtotal 0.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"base-state","state":{"nums":[1,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"options":[{"id":"one-and-zero","label":"Subtotal 0 holds 1; every larger subtotal starts at 0","rationale":"The empty sequence is the one way to total 0. A number that lands on its subtotal then reads that 1 and counts itself once; unsolved subtotals begin with no ways.","isCorrect":true},{"id":"all-zero","label":"Every subtotal, including 0, starts at 0","rationale":"Then a number landing on its subtotal adds 0 and is never counted. Subtotal 0 must start at 1.","isCorrect":false},{"id":"all-one","label":"Every subtotal starts at 1","rationale":"No subtotal above 0 has a known sequence before the sweep runs. Seeding them at 1 invents ways the transitions never justified.","isCorrect":false}],"answer":"Subtotal 0 holds 1 for the empty sequence, and every larger subtotal starts at 0. A number reaching its own subtotal adds that single base way."},{"id":"approach-selection","chapter":"The rule","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[1,1,0,0,0],"i":1,"labels":{"nums":"dp","i":"total"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Each subtotal gathers from the ones behind it","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,0,0,0,0],"i":1,"labels":{"nums":"dp","i":"total"}}}]},"body":["The table starts with subtotal 0 at one way and every larger subtotal at zero.","Sweep subtotals from 1 upward. At each subtotal, try every number as the final step, and add into the subtotal the count already stored at total minus that number.","Because the final number is what splits the sequences, 1+2 and 2+1 are counted separately. Trace nums = [1, 2, 3] and target = 4 and read off what the target cell holds."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the table","title":"Trace the subtotal sweep","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fill-2","state":{"nums":[1,1,0,0,0],"i":2,"labels":{"nums":"dp","i":"total"}}},{"id":"fill-3","state":{"nums":[1,1,2,0,0],"i":3,"labels":{"nums":"dp","i":"total"}}},{"id":"fill-4","state":{"nums":[1,1,2,4,0],"i":4,"labels":{"nums":"dp","i":"total"}}}]},"beats":[{"id":"fill-2","title":"At subtotal 2, what is the count?","summary":"Subtotals 0 and 1 already hold 1 and 1. Numbers 1 and 2 fit inside subtotal 2; 3 does not.","prompt":"The sweep has reached subtotal 2.","options":[{"id":"two","label":"2","rationale":"Number 1 reads subtotal 1 (count 1) and number 2 reads subtotal 0 (count 1), so dp[2] = 1 + 1 = 2: the sequences 1+1 and 2.","isCorrect":true},{"id":"one","label":"1","rationale":"That counts only the all-1s sequence. The number 2 also reaches subtotal 2 from subtotal 0, so there are two sequences.","isCorrect":false},{"id":"three","label":"3","rationale":"Number 3 is larger than subtotal 2, so it cannot be the final step here. Only 1 and 2 contribute, giving 2.","isCorrect":false}],"answer":"2. dp[2] = dp[1] + dp[0] = 1 + 1, for the sequences 1+1 and 2."},{"id":"fill-3","title":"At subtotal 3, what should the count be?","summary":"Subtotals 0, 1, and 2 now hold 1, 1, and 2. Every number in nums fits inside subtotal 3.","prompt":"The sweep has reached subtotal 3.","options":[{"id":"four","label":"Four: dp[2] + dp[1] + dp[0] = 2 + 1 + 1","rationale":"Final number 1 reads dp[2] = 2, number 2 reads dp[1] = 1, number 3 reads dp[0] = 1, so the three reduced counts sum to 4.","isCorrect":true},{"id":"prev-only","label":"Two: just dp[2], the subtotal one step behind","rationale":"That reads only the count for final number 1. Final numbers 2 and 3 reach subtotal 3 from dp[1] and dp[0], so those counts must be added too, giving 4.","isCorrect":false},{"id":"one-per-fit","label":"Three: one for each number that fits","rationale":"All three numbers fit inside subtotal 3, but the count is not how many fit. Each fitting number contributes the count at its reduced subtotal, so 2 + 1 + 1 = 4.","isCorrect":false}],"answer":"dp[3] = dp[2] + dp[1] + dp[0] = 2 + 1 + 1 = 4. Each fitting final number contributes the count at its reduced subtotal."},{"id":"fill-4","title":"At subtotal 4, what does the function return?","summary":"Subtotals 1, 2, and 3 now hold 1, 2, and 4. Subtotal 4 is the target.","prompt":"The sweep reaches subtotal 4, the target.","options":[{"id":"seven","label":"7","rationale":"Final number 1 reads dp[3] = 4, number 2 reads dp[2] = 2, number 3 reads dp[1] = 1, so dp[4] = 4 + 2 + 1 = 7, the answer.","isCorrect":true},{"id":"four","label":"4, the same as subtotal 3","rationale":"Subtotal 4 reads reduced subtotals 3, 2, and 1, so its count rises to 7.","isCorrect":false},{"id":"eight","label":"8","rationale":"Only the reduced subtotals that a fitting number reaches are added: 4 + 2 + 1 = 7, not 8.","isCorrect":false}],"answer":"7. dp[4] = dp[3] + dp[2] + dp[1] = 4 + 2 + 1, and that target cell is what the function returns."}]},{"id":"loop-order-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could each number finish its own sweep instead?","summary":"Looping each number on the outside and sweeping subtotals inside looks like the same two loops reordered, and it still fills the table left to right. Watch what changes when one number finishes all of its subtotals before the next number runs.","workspacePanel":"trace","pitfall":"The table below loops numbers on the outside and subtotals on the inside.","whyItMatters":"With nums = [1, 2, 3] and target = 4 the ordered answer is 7, but numbers-outside returns 4: it counts each multiset once, so 1+2 and 2+1 collapse into a single sequence. Keep the subtotal loop on the outside so every subtotal weighs every final number, and each distinct order is counted.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"dp = [0] * (target + 1)\ndp[0] = 1\nfor num in nums:\n    for total in range(num, target + 1):\n        dp[total] += dp[total - num]\nreturn dp[target]","steps":[{"id":"after-1","title":"After number 1 sweeps","codeLine":5,"summary":"nums = [1, 2, 3], target = 4. Number 1 sweeps every subtotal, carrying the single all-1s sequence, so dp becomes [1, 1, 1, 1, 1].","state":{"nums":[1,1,1,1,1],"i":4,"labels":{"nums":"dp","i":"total"}}},{"id":"enter-2","title":"Number 2 starts its own sweep","codeLine":3,"summary":"Number 1 is fully finished before number 2 begins. From here a 2 only ever extends a subtotal already built from 1s, so it lands as the larger number, never with a 1 placed after it.","state":{"nums":[1,1,1,1,1],"i":2,"labels":{"nums":"dp","i":"total"}}},{"id":"after-2","title":"After number 2 sweeps, subtotal 3 reads 2","codeLine":5,"summary":"Subtotal 3 adds dp[1] = 1, giving dp[3] = 2: the sequences 1+1+1 and 1+2. The order 2+1 is gone, because number 1 already finished and can no longer follow a 2.","state":{"nums":[1,1,2,2,3],"i":3,"labels":{"nums":"dp","i":"total"}}},{"id":"after-3","title":"After number 3 sweeps, the target reads 4","codeLine":5,"summary":"Subtotal 4 adds dp[1] = 1 for number 3, landing dp[4] = 4: only the four multisets. The ordered count of 7 has collapsed.","state":{"nums":[1,1,2,3,4],"i":4,"labels":{"nums":"dp","i":"total"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dp = Array((target + 1)).fill(0);\ndp[0] = 1;\nfor (const num of nums) {\n    for (let total = num; total < (target + 1); total++) {\n        dp[total] = (dp[total] + dp[(total - num)]);\n    }\n}\nreturn dp[target];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dp = Array((target + 1)).fill(0);\ndp[0] = 1;\nfor (const num of nums) {\n    for (let total = num; total < (target + 1); total++) {\n        dp[total] = (dp[total] + dp[(total - num)]);\n    }\n}\nreturn dp[target];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] dp = new int[(target + 1)];\ndp[0] = 1;\nfor (Integer num : nums) {\n    for (int total = num; total < (target + 1); total++) {\n        dp[total] = (dp[total] + dp[(total - num)]);\n    }\n}\nreturn dp[target];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dp = Enumerable.Repeat<int>(0, target + 1).ToList();\ndp[0] = 1;\nforeach (int num in nums) {\n    for (int total = num; total < target + 1; total++) {\n        dp[total] = dp[total] + dp[total - num];\n    }\n}\nreturn dp[target];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dp = vector<int>((target + 1), 0);\ndp[0] = 1;\nfor (int num : nums) {\n    for (int total = num; total < (target + 1); total++) {\n        dp[total] = (dp[total] + dp[(total - num)]);\n    }\n}\nreturn dp[target];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[1,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"body":["Counting each order came from sweeping subtotals on the outside, every subtotal weighing every final number.","Push on the boundaries next. Try target = 0, then try a target smaller than every number in nums."]},{"id":"zero-target-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"How many ordered sequences make a target of 0?","summary":"Target zero is the base every larger subtotal reads from.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-target-state","state":{"nums":[1],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"options":[{"id":"one","label":"1, the empty sequence","rationale":"Appending no numbers is the single ordered sequence that totals 0. That is exactly the subtotal-0 seed every larger subtotal builds on.","isCorrect":true},{"id":"zero","label":"0, since no numbers are used","rationale":"Using no numbers is one valid sequence. The count is 1.","isCorrect":false},{"id":"len-nums","label":"One per number in nums","rationale":"No single number totals 0; the only way to reach 0 is to append nothing. The count is 1.","isCorrect":false}],"answer":"1. The empty sequence is the one ordered way to total 0, which is why subtotal 0 is seeded at 1."},{"id":"unreachable-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if no number can reach the target?","summary":"Some targets sit below every number in nums.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unreachable-state","state":{"nums":[1,0],"i":1,"labels":{"nums":"dp","i":"total"}}}]},"options":[{"id":"zero","label":"0, because the fit check blocks every number","rationale":"For nums = [2, 5, 10], target 1, every number is larger than 1, so the guard skips them all and subtotal 1 keeps its starting count of 0.","isCorrect":true},{"id":"minus-one","label":"-1, since the target is impossible","rationale":"This problem reports a count, never -1. An unreachable target simply has 0 ordered sequences.","isCorrect":false},{"id":"one","label":"1, the empty sequence still counts","rationale":"The empty sequence totals 0, not 1. No number fits into subtotal 1, so its count stays 0.","isCorrect":false}],"answer":"0. Every number exceeds the target, so the fit guard adds nothing and the target keeps its starting count of 0."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Subtotals sweep on the outside, numbers on the inside, so every order is counted.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,0,0,0,0],"i":0,"labels":{"nums":"dp","i":"total"}}}]},"body":["Make a count table sized to the target, all zeros except subtotal 0 seeded at one empty sequence. Sweep subtotals upward, and at each one add the count from total minus every number that fits. Read the answer off the target cell."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the ordered-count table","summary":"Now build it: size the table and seed subtotal 0 at one, sweep subtotals upward, try each number as the final step, add the count from total minus that number when it fits, then return the target cell.","workspacePanel":"code","checkpoints":[{"id":"init-dp-array","title":"Initialize the count table","description":"Create a table for every subtotal from 0 through target and seed one way to reach subtotal 0.","commonMistakes":["Leaving the zero subtotal at 0","Sizing the table to target instead of target + 1"],"hint":"There is exactly one ordered sequence that sums to 0: the empty one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_count_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Allocate the counting table over subtotals and seed the zero subtotal with one empty ordered sequence.","doneWhen":"This step is done when the table covers target + 1 cells, every count starts at zero, and the zero subtotal is set to one before any transition runs.","shouldFailWhen":"This step should fail if the table is the wrong size, the zero base count is missing, or non-base cells start as prefilled answers.","roles":["count table over subtotals","zero subtotal base case","ordered-sequence count"],"mustProve":["The count table has one cell for each subtotal from 0 through target.","The zero subtotal is seeded with exactly one way before the transitions run."],"mustNotAccept":["A scalar counter with no per-subtotal state.","A table that seeds every subtotal to one."],"equivalentVariants":["Use a list, array, or vector of zero counts with length target + 1.","Seed the zero index to one before the loops."],"proofSnippets":[{"id":"py-combination-sum-iv-init-dp-array","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        return 0"}]}},{"id":"outer-loop","title":"Sweep every subtotal in increasing order","description":"Visit each subtotal from 1 through target as the outer loop, so every subtotal is settled before larger ones read it.","commonMistakes":["Looping numbers first, which counts each multiset once instead of each order","Stopping before the target subtotal"],"hint":"Each subtotal must gather ways from every possible final number, so the subtotal is the outer axis.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Drive the transition by visiting every subtotal from one through target in an outer pass.","doneWhen":"This step is done when the code scans subtotal values from one to target around the candidate-number loop.","shouldFailWhen":"This step should fail if there is no subtotal scan, or the loops nest so that each multiset is counted once instead of each ordering.","roles":["subtotal index","target boundary","outer state-space scan"],"mustProve":["The loop visits the subtotal cells in the table.","The subtotal scan wraps the candidate-number choice."],"mustNotAccept":["Only looping over input numbers without a subtotal scan.","A combination-counting loop order that fixes one number order."],"equivalentVariants":["Use range(1, target + 1) or an equivalent inclusive subtotal loop."],"proofSnippets":[{"id":"py-combination-sum-iv-outer-loop","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            pass\n        return 0"}]}},{"id":"inner-loop","title":"Try each number as the final step","description":"For the current subtotal, scan every number in nums as a possible last number of the ordered sequence.","commonMistakes":["Trying only one number","Breaking out before every candidate is tried"],"hint":"Any number can be the last step of an ordered sequence, as long as it fits inside the subtotal.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Nest a scan over candidate numbers inside the subtotal scan so each subtotal can absorb every possible final number.","doneWhen":"This step is done when each subtotal iteration considers the numbers in nums as the final choice.","shouldFailWhen":"This step should fail if the code never scans the candidate numbers inside the subtotal loop.","roles":["candidate number","nested choice scan","current subtotal"],"mustProve":["The code has a nested scan over candidate numbers inside the subtotal loop."],"mustNotAccept":["Hard-coding one candidate.","Using only the first number."],"equivalentVariants":["Loop directly over the values or over indices into nums."],"proofSnippets":[{"id":"py-combination-sum-iv-inner-loop","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                pass\n        return 0"}]}},{"id":"dp-update","title":"Add the ways from the reduced subtotal","description":"When a number fits inside the subtotal, add the count from total minus that number into the current subtotal.","commonMistakes":["Replacing the count instead of adding to it","Reading the wrong predecessor subtotal"],"hint":"Every ordered sequence for total minus num becomes one for total by appending num as the final step.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"applies_additive_subset_transition","scope":"dp-update","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Apply the additive count recurrence from the reduced subtotal into the current subtotal when the number fits.","doneWhen":"This step is done when the code guards on whether the number fits and adds the count at total minus the number into the current subtotal.","shouldFailWhen":"This step should fail if the update overwrites instead of adds, reads the wrong predecessor, or stores a boolean instead of a count.","roles":["current subtotal count","candidate number","reduced subtotal count","additive recurrence"],"mustProve":["The transition is guarded by whether the candidate number fits inside the subtotal.","The update adds the reduced subtotal count into the current subtotal count."],"mustNotAccept":["Assigning a boolean reachable flag instead of a count.","Updating the current subtotal from itself."],"equivalentVariants":["Use dp[total] += dp[total - num].","Use dp[total] = dp[total] + dp[total - num]."],"proofSnippets":[{"id":"py-combination-sum-iv-dp-update","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                if num <= total:\n                    dp[total] += dp[total - num]\n        return 0"}]}},{"id":"return-result","title":"Return the target count","description":"Return the number of ordered sequences stored at the target subtotal.","commonMistakes":["Returning the whole table","Returning the last candidate count instead of the target cell"],"hint":"The target cell holds every ordered sequence that sums to target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal count stored at the target subtotal.","doneWhen":"This step is done when the function returns the table cell at the target index after every subtotal is filled.","shouldFailWhen":"This step should fail if the code returns a scalar loop variable, the wrong index, or the full table.","roles":["target subtotal","terminal table cell","final answer"],"mustProve":["The returned value reads the table at the target index."],"mustNotAccept":["Returning the entire table.","Returning the zero subtotal."],"equivalentVariants":["Return the target-indexed cell from the one-dimensional table."],"proofSnippets":[{"id":"py-combination-sum-iv-return-result","language":"python","code":"class Solution:\n    def combinationSum4(self, nums: list[int], target: int) -> int:\n        dp = [0] * (target + 1)\n        dp[0] = 1\n        for total in range(1, target + 1):\n            for num in nums:\n                if num <= total:\n                    dp[total] += dp[total - num]\n        return dp[target]"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"Each order is counted because every subtotal weighs every possible final number.","body":["Seed subtotal 0 at one empty sequence, then sweep subtotals upward, adding the count at total minus each number that fits.","Sweeping subtotals on the outside lets a subtotal read every reduced subtotal, so 1+2 and 2+1 are counted as two distinct sequences."],"takeaways":[{"title":"Subtotals outside, numbers inside","body":"Each subtotal weighing every final number is what keeps distinct orders apart, the opposite of the multiset count."},{"title":"Split by the final number","body":"dp[total] sums dp[total - num] over every fitting num, so each sequence is counted once, under its last step."},{"title":"Subtotal zero anchors it","body":"The one empty sequence at subtotal 0 is the base every transition reads, so a number reaching its target counts itself once."},{"title":"The cost the table buys","body":"Every subtotal tries every number once, so the run is O(target * n) time for n numbers, and the table stores one count per subtotal, so O(target) space, down from the naive exponential search."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
