The knapsack problem
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A bag holds 5 kg and three items compete for the space. Greedy by value per kg picks wrong, and trying every subset doubles the work with each new item. A table of small questions, best[i][c], solves it: each cell decides once about one item, skip it or take it. Watch the 24 cells fill, walk back from the corner to find the items, and see why the cost O(nW) is called pseudo-polynomial. It uses the state-and-transition recipe from "Defining states and transitions", and the Software lesson "Dynamic programming" covers memoisation and tables.
Pack a bag
A bag holds 5 kg. Item A weighs 1 kg and is worth $2, B weighs 3 kg for $4, C weighs 4 kg for $5. Each item goes in whole or not at all: the 0/1 knapsack. Goal: the most value.
capacity W = 5 kg, n = 3 items A 1 kg $2 $2.00 per kg B 3 kg $4 $1.33 per kg C 4 kg $5 $1.25 per kg take each item whole (1) or not at all (0) maximise total value, total weight ≤ 5
اقرأ الدرس خطوة بخطوة
Pack a bag
A bag holds 5 kg. Item A weighs 1 kg and is worth $2, B weighs 3 kg for $4, C weighs 4 kg for $5. Each item goes in whole or not at all: the 0/1 knapsack. Goal: the most value.
capacity W = 5 kg, n = 3 items A 1 kg $2 $2.00 per kg B 3 kg $4 $1.33 per kg C 4 kg $5 $1.25 per kg take each item whole (1) or not at all (0) maximise total value, total weight ≤ 5Greedy picks wrong
Greedy by value per kg takes A, then B: $6, and C no longer fits. Yet A + C weighs exactly 5 kg and is worth $7. Trying all 2ⁿ subsets finds it, but doubles the work with every new item.
greedy: best $ per kg first, whole items only A $2.00/kg take room 5 → 4 B $1.33/kg take room 4 → 1 C $1.25/kg 4 kg > 1 kg left: skip greedy total $6 brute force: 8 subsets, best A + C = $7 30 items would mean 2³⁰ = 1,073,741,824 subsetsOne cell per small question
Let best[i][c] be the most value from the first i items in a bag of c kg. The table has rows 0, A, B, C (items up to that one) and columns 0 to 5 kg. No items or no room is worth $0.
state: best[i][c] = most value using items 1..i with capacity c rows i = 0, 1 (A), 2 (B), 3 (C) columns c = 0, 1, 2, 3, 4, 5 4 × 6 = 24 cells base cases: best[0][c] = 0, best[i][0] = 0 >>> [[0] * (5 + 1)] [[0, 0, 0, 0, 0, 0]]Skip it or take it
Each cell decides about one item. Skip it: keep the cell straight above. Take it, if it fits: its value plus the cell above and w columns left. Keep the larger. Row A at 1 kg: max(0, 2 + 0) = 2.
best[i][c] = max( best[i-1][c], # skip item i v_i + best[i-1][c - w_i]) # take it, if w_i ≤ c best[A][1] = max(best[0][1], 2 + best[0][0]) = max(0, 2 + 0) = 2 each cell reads only the row aboveFill row A
The rest of row A: from 1 kg up, item A always fits, so each cell is max(0, 2 + 0) = 2. With only item A to choose from, the best you can do is $2, whatever the bag size.
row A (w = 1, v = 2) c=1: max(0, 2 + 0) = 2 c=2: max(0, 2 + 0) = 2 c=3: max(0, 2 + 0) = 2 c=4: max(0, 2 + 0) = 2 c=5: max(0, 2 + 0) = 2 best[A] = [0, 2, 2, 2, 2, 2]Fill row B
B weighs 3 kg, so at 1 and 2 kg it cannot fit: copy the cell above. At 3 kg, taking B gives 4 + 0 = 4. At 4 kg, 4 + best[A][1] = 4 + 2 = 6: B and A together.
row B (w = 3, v = 4) c=1: 3 > 1, skip only = 2 c=2: 3 > 2, skip only = 2 c=3: max(2, 4 + 0) = 4 c=4: max(2, 4 + 2) = 6 c=5: max(2, 4 + 2) = 6 best[B] = [0, 2, 2, 4, 6, 6]Fill row C
C weighs 4 kg. At 4 kg, taking C gives 5 + 0 = 5, less than the 6 above, so skip it. At 5 kg, 5 + best[B][1] = 5 + 2 = 7 beats 6. The corner cell holds the answer: $7.
row C (w = 4, v = 5) c=1: 4 > 1, skip only = 2 c=2: 4 > 2, skip only = 2 c=3: 4 > 3, skip only = 4 c=4: max(6, 5 + 0) = 6 c=5: max(6, 5 + 2) = 7 best[C] = [0, 2, 2, 4, 6, 7] answer best[C][5] = 7Walk back to the items
Which items? Start at the corner. 7 differs from the 6 above, so C was taken: go up and 4 columns left. 2 equals the 2 above, so B was skipped. 2 differs from 0, so A was taken: A + C, $7.
walk back from best[C][5] best[C][5] = 7 ≠ best[B][5] = 6 → take C, c = 5 − 4 = 1 best[B][1] = 2 = best[A][1] = 2 → skip B best[A][1] = 2 ≠ best[0][1] = 0 → take A, c = 1 − 1 = 0 bag: A + C, 1 + 4 = 5 kg, $2 + $5 = $7Cost: n times W
The table has (n + 1)(W + 1) = 4 × 6 = 24 cells, each one max, so the time is O(nW). That is pseudo-polynomial: W is a number, and one more digit in W makes the table ten times wider.
cells: (n + 1)(W + 1) = 4 × 6 = 24 work per cell: one max → O(1) time O(nW), space O(nW) for the full table (O(W) if you keep one row and run c downward) input size: n items + about log₂ W bits for W W = 5 → 6 columns; W = 50,000 → 50,001 columns >>> knapsack([(1, 2), (3, 4), (4, 5)], 5)[-1][-1] 7
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A bag holds 5 kg. A is 1 kg for $2, B is 3 kg for $4, C is 4 kg for $5. What does greedy by value per kg pack, and what is the best?
Greedy takes A ($2/kg) and B ($1.33/kg), leaving 1 kg, so C (4 kg) no longer fits: $6. A + C weighs exactly 5 kg and is worth $7. B + C weighs 7 kg, too much.
02Which recurrence fills best[i][c] for the 0/1 knapsack (item i has weight w and value v)?
Skip item i: keep the best from the earlier items at the same capacity. Take it: its value plus the best from the earlier items in the room left, c − w. Reading row i − 1 for the take is what stops an item being used twice.
03In the finished table, best[C][5] = 7 and best[B][5] = 6. What does that tell you?
The corner differs from the cell above, so the best answer used item C. Go up one row and 4 columns left (C weighs 4 kg) to best[B][1], and keep walking back.
04With n items and capacity W, how many cells does the full table have?
Rows 0 to n and columns 0 to W: (n + 1)(W + 1) cells, each one max, so O(nW) time. Here that is 4 × 6 = 24.
05Why is O(nW) called pseudo-polynomial?
Each extra digit in W makes the table about ten times wider while the input grows by one digit. The time is polynomial in the value W, not in the number of bits needed to write it.
المسرد
- 0/1 knapsack
- Choose items, each whole or not at all, with total weight at most the capacity W, to get the most total value.
- Fractional knapsack
- The version where items can be cut. Greedy by value per kg is exactly right there, but not for whole items.
- Capacity (W)
- The most weight the bag can hold. In the table it sets the number of columns, W + 1.
- State best[i][c]
- The most value you can get from the first i items in a bag of capacity c.
- Skip or take
- The transition: keep best[i−1][c], or add item i's value to best[i−1][c − w]. The larger wins.
- Walk back
- Recovering the chosen items from the finished table: where a cell differs from the one above, its item was taken.
- Pseudo-polynomial
- Polynomial in the numeric value of an input such as W, but not in the number of bits used to write that value.
الملاحظات والمصادر
- The recurrence is the one in MIT 6.006 (Recitation 18) and in Sedgewick and Wayne's Knapsack.java: best[i][c] = max(best[i−1][c], v_i + best[i−1][c − w_i]), the second option only when w_i ≤ c, with best[0][c] = best[i][0] = 0.
- Greedy by value per kg is exactly right for the fractional knapsack, where items can be cut (see the lesson "Greedy choices"). With whole items only it can fail, as A + B = $6 versus A + C = $7 shows here.
- Each row reads only the row above, so one list of W + 1 numbers is enough if c runs from W down to w: then best[c − w] still holds the previous row's value when it is read. Running c upward would let one item be taken twice (that is the unbounded knapsack).
- O(nW) looks polynomial, but W is a value, not a count: it takes only about log₂ W bits to write down. Doubling the number of digits in W squares the table width, so the running time is exponential in the input's length. That is why the time is called pseudo-polynomial; the 0/1 knapsack is NP-hard in general.
- The code is real Python 3: knapsack([(1, 2), (3, 4), (4, 5)], 5) returns the four rows [0, 0, 0, 0, 0, 0], [0, 2, 2, 2, 2, 2], [0, 2, 2, 4, 6, 6] and [0, 2, 2, 4, 6, 7]. row = up[:] copies the row above, so cells with c < w keep the skip value.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Recitation 18: Subset Sum Variants (0-1 Knapsack)
- MIT 6.006 (Spring 2020), Lecture 18: Dynamic Programming, Part 4: Rods, Subset Sum, Pseudopolynomial
- Sedgewick and Wayne, Computer Science: Knapsack.java (dynamic programming, time and space N × W)
- Sedgewick and Wayne, Algorithms 4th ed., §6.6 Intractability (Knapsack is NP-complete)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §15.2
- Python Standard Library: Built-in Types (range, slicing and copies of lists)
اختبار يتاح بعد الخطوة الأخيرة.