From 9c0fe0ff494aa14ba28816b7f5fec6e6a7b61687 Mon Sep 17 00:00:00 2001 From: haofeng <852172305@qq.com> Date: Sun, 6 Jun 2021 15:55:35 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C=E5=85=A8=E8=83=8C?= =?UTF-8?q?=E5=8C=85.md=20=E6=B7=BB=E5=8A=A0=20python3=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../背包问题理论基础完全背包.md | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index 02785ad7..9997dff3 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -179,9 +179,45 @@ int main() { Java: - Python: +```python3 +# 先遍历物品,再遍历背包 +def test_complete_pack1(): + weight = [1, 3, 4] + value = [15, 20, 30] + bag_weight = 4 + + dp = [0]*(bag_weight + 1) + + for i in range(len(weight)): + for j in range(weight[i], bag_weight + 1): + dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) + + print(dp[bag_weight]) + +# 先遍历背包,再遍历物品 +def test_complete_pack2(): + weight = [1, 3, 4] + value = [15, 20, 30] + bag_weight = 4 + + dp = [0]*(bag_weight + 1) + + for j in range(bag_weight + 1): + for i in range(len(weight)): + if j >= weight[i]: dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) + + print(dp[bag_weight]) + + +if __name__ == '__main__': + test_complete_pack1() + test_complete_pack2() +``` + + + Go: