From ecd98c9a79e1e3efbde2dc140d9adc7b2af93c3b Mon Sep 17 00:00:00 2001 From: Kelvin Date: Tue, 15 Jun 2021 21:06:42 -0400 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-2.md?= =?UTF-8?q?=20Python3=20=E5=AE=9E=E7=8E=B0=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-2.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 075bb5b1..aee1a929 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -242,7 +242,24 @@ Java: Python: +```python +def test_1_wei_bag_problem(): + weight = [1, 3, 4] + value = [15, 20, 30] + bag_weight = 4 + # 初始化: 全为0 + dp = [0] * (bag_weight + 1) + # 先遍历物品, 再遍历背包容量 + for i in range(len(weight)): + for j in range(bag_weight, weight[i] - 1, -1): + # 递归公式 + dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) + + print(dp) + +test_1_wei_bag_problem() +``` Go: ```go