競賽程式設計簡單

0-1 背包

“0-1 Knapsack”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 knapsack(W, wt, val, n),使用重量為 wt 且值為 val 的物品找出容量為 W 的背包中可以放入的最大值。您不能拆分項目;你要么拿走一件物品,要么留下它。

約束條件
  • 1 <= n <= 100
  • 1 <= W <= 1000
  • 1 <= wt[i], val[i] <= 1000

範例

Example 1
Input
knapsack(50, [10, 20, 30], [60, 100, 120], 3)
Output
220
Explanation

By taking items with weight 20 and 30, the total weight is 50, and the value is 100 + 120 = 220.

Example 2
Input
knapsack(10, [5, 4, 6, 3], [10, 40, 30, 50], 4)
Output
90
Explanation

By taking items of weight 4 and 3, the total weight is 7, and the value is 40 + 50 = 90.

Need a Hint?
考慮使用動態程式特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。