From 35444fd703213cd97ef526dc686ec8c7faaee33a Mon Sep 17 00:00:00 2001 From: liulei <718356979@qq.com> Date: Tue, 6 Jul 2021 15:03:26 +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=20java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../背包问题理论基础完全背包.md | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index a5a708cf..1ad09c4b 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -176,9 +176,48 @@ int main() { ## 其他语言版本 - Java: +```java + //先遍历物品,再遍历背包 + private static void testCompletePack(){ + int[] weight = {1, 3, 4}; + int[] value = {15, 20, 30}; + int bagWeight = 4; + int[] dp = new int[bagWeight + 1]; + for (int i = 0; i < weight.length; i++){ + for (int j = 1; j <= bagWeight; j++){ + if (j - weight[i] >= 0){ + dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); + } + } + } + for (int maxValue : dp){ + System.out.println(maxValue + " "); + } + } + + //先遍历背包,再遍历物品 + private static void testCompletePackAnotherWay(){ + int[] weight = {1, 3, 4}; + int[] value = {15, 20, 30}; + int bagWeight = 4; + int[] dp = new int[bagWeight + 1]; + for (int i = 1; i <= bagWeight; i++){ + for (int j = 0; j < weight.length; j++){ + if (i - weight[j] >= 0){ + dp[i] = Math.max(dp[i], dp[i - weight[j]] + value[j]); + } + } + } + for (int maxValue : dp){ + System.out.println(maxValue + " "); + } + } +``` + + + Python: ```python3