0-1 背包动态规划
观察经典背包 DP 表的填充过程。每个格子回答:用前 i 个物品、容量 w 时,最大价值是多少?
9 分钟难度 3/3交互演示区域不展示广告。
Try:
5 items · capacity 8
Capacity8Items5Best value11Step54 / 54
| Item | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A (2kg) | 0 | 0 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |
| B (3kg) | 0 | 0 | 3 | 4 | 4 | 7 | 7 | 7 | 7 |
| C (4kg) | 0 | 0 | 3 | 4 | 5 | 7 | 8 | 9 | 9 |
| D (5kg) | 0 | 0 | 3 | 4 | 5 | 7 | 8 | 9 | 10 |
| E (1kg) | 0 | 2 | 3 | 5 | 6 | 7 | 9 | 10 | 11 |
Item E, capacity 8: best value 11.
Skip the item and keep 10; take it and add 2 to 9, giving 11.
Best value 11B (3kg, 4) · C (4kg, 5) · E (1kg, 2)
Each cell compares skipping the current item with taking it plus the best earlier result. Edit the items or capacity to turn this into a small planning tool. After completion, Trace winners follows the chosen cells back through the table.
你看到的是什么
1
行是物品,列是容量。dp[i][w] 表示使用前 i 个物品、容量为 w 时的最大价值。
2
对每个物品,要么跳过(取上方格子),要么在放得下时装入(价值加上 w - 重量 处的格子)。
3
填满后,从右下角回溯,就能看出最终选了哪些物品。
为什么重要
背包问题是动态规划的入门模型:资源分配、预算、排程和大量优化问题都共享同样的填表结构。
复杂度与细节
时间:O(nW);完整表格空间:O(nW)(滚动数组可降到 O(W))。
常见问题
为什么背包问题是伪多项式?+
运行时间取决于容量数值 W,而不只是物品数量。W 很大时,即使物品很少,表格也会很大。
回溯步骤在做什么?+
从 dp[n][W] 开始:如果当前价值来自该物品,就选中它并跳到 w - 重量;否则向上移动一行。