Unit 7 of 9 · about 4 hours · derive, implement
Knapsack, subset and bitmask dynamic programming
One table shape answers min-coins, counting and feasibility. The loop direction decides whether an item is reusable.
You'll be able to
- Derive take-or-skip recurrences with the correct inner-loop direction for versus unbounded choice.
- Reduce subset-sum and counting variants to one knapsack table.
- Encode small-set state as bitmasks and bound the state cost.
Covers
Read
In this order, only the parts listed
0 of 4 done
- knapsack and the backward inner loopDSA Handbook - dynamic programming
The 1D table fill; Why the inner loop sweeps right-to-left; Worked example: LC 416 on
[1, 5, 11, 5]; Reformulations: when the problem doesn't say "knapsack" (LC 494, 1049, 474) - Unbounded knapsack and the reversed loopDSA Handbook - dynamic programming
What changes from knapsack; The mechanics: filling left to right; Counting unordered combinations: LC 518; Counting ordered sequences: LC 377
- Bitmask state for small setsDSA Handbook - dynamic programming
The pattern; Worked example: LC 847 on a 3-node line; What it actually costs; Permutation / assignment: position is
popcount(mask)(LC 526) - Subset Sum and the Nadiria change problemAlgorithms - dynamic programming
Section 3.8 (pp. 116-117): recurrence with the table, and Exercise 1 Nadiria change (p. 123): greedy failure first, then recurrence, then DP
Focus on
- sweeps capacity right to left so item cannot fund itself in the same pass. Unbounded sweeps left to right so already includes item .
- Subset Sum is pseudopolynomial: is a value, not the input size. Tabulation loses to backtracking when dwarfs .
- Bitmask state costs subsets times transitions. It fits only small ground sets; that boundary is the content, not a footnote.
Common mistakes · 3
- Sweeping capacity left to right. Item then reuses its own update and the table silently becomes unbounded.
- Reading min-coins -1 as zero ways. Coin Change returns -1 when unreachable; Coin Change II returns 0 ways. Different families, different sentinels.
- Applying bitmask DP past without counting. rows times columns already exceeds ten million cells; state the bound first.
Try it yourself
Closed-book, before checking anything
coin_change([1,2,5], 11) = 3, coin_change_ii(5, [1,2,5]) = 4, can_partition([1,5,11,5]) = True and can_partition([1,2,3,5]) = False. Also show largest-first greedy on ([1,3,4], 6) gives 3 coins versus optimal 2. State the amounts and all five expected outputs.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does the inner loop run right to left?Answer
Left to right lets read written in the same item pass, reusing item . Right to left keeps every read on the previous item row.
2.Coins
[1,3,4], amount 6: what does largest-first greedy give and why is it wrong?Answercoins. Optimal is . Greedy commits to 4 without comparing the two-coin completion; only the recurrence compares all last-coin choices.
3.Subset Sum runs . Why is that not polynomial?Answer
measures a value in the input, which takes bits to write. The bound is polynomial in the numeric value but exponential in the input length.
4.When is bitmask state the only state that fits?Answer
When feasibility depends on exactly which items are used, not just how many or how much. Assignment and visit-all paths need the subset identity itself.
Practice
- LeetCode 322 - Coin Change
Attempt cold. Check
([1,2,5], 11) = 3,([2], 3) = -1and([1], 0) = 0, then submit.Attempt cold: write the reuse direction before coding. After submitting, read the AlgoMaster Coin Change lesson (https://algomaster.io/learn/dsa/coin-change).
- LeetCode 416 - Partition Equal Subset Sum
Check
[1,5,11,5] = Trueand[1,2,3,5] = False, then submit.Reduce to subset sum with target . After submitting, compare with the DSA Handbook knapsack-01 reformulation section.
You're done when
The five reproduce numbers come out of a blank file, and you can state each loop direction and why.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 6 more in the section
- DSA Handbook - dynamic programmingHandbook Academy · primary
Study Part 9 in order from state and recurrence through sequence, grid, tree and bitmask families. For every example, close the page and reconstruct the state, transition and evaluation order.
- Algorithms - dynamic programmingJeff Erickson · required
Use the dynamic-programming chapter to derive states and recurrences from first principles and to separate DP from greedy reasoning and shortest paths.
Also in this section
- AlgoMaster DSA - dynamic programming sliceAlgoMaster · required
Attempt Coin Change, Longest Common Subsequence and House Robber III cold. Write the state, transition, base case and evaluation order first; compare against brute force on small inputs and reconstruct a witness when available.
- Hypothesis - exhaustive and differential DP testsHypothesis · support
Generate small valid instances, compare memoized, tabulated and exhaustive results, and retain shrunk failures for wrong state, base case, order and compression defects.
- NeetCode - unseen mixed problemsNeetCode · optional
Use two tag-hidden mixed problems as the final transfer test. One must require rejecting a tempting greedy or insufficient-state solution with a counterexample.
- Python sys: recursion limitPython Software Foundation · reference
Read
sys.getrecursionlimitandsys.setrecursionlimit: the limit guards the C stack and its safe maximum is platform-dependent. Check the default withgetrecursionlimit(1000 on CPython 3.13), raise it once for memoized DP, or switch to tabulation for deep inputs. - Erickson lecture note D - Advanced Dynamic ProgrammingJeff Erickson · reference
Read Section D.1 (Saving Space: Divide and Conquer) for the Hirschberg Half-table split that recovers an optimal edit sequence in space.
- Erickson lecture note J - Approximation AlgorithmsJeff Erickson · reference
Read Section J.1 (Load Balancing) for the Partition reduction that makes exact scheduling NP-hard, the
GreedyLoadBalanceheuristic, and Theorem J.1 with its factor-2 proof.