From a0824a84ec24bec4037087ba7084861885463b8f Mon Sep 17 00:00:00 2001 From: fusunx <1102654482@qq.com> Date: Thu, 5 Aug 2021 08:02:52 +0800 Subject: [PATCH] =?UTF-8?q?=E8=83=8C=E5=8C=85=E9=97=AE=E9=A2=98=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C=E5=85=A8=E8=83=8C=E5=8C=85?= =?UTF-8?q?=20Javascript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../背包问题理论基础完全背包.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index a5a708cf..2cbc7bb8 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -272,7 +272,38 @@ func main() { fmt.Println(test_CompletePack2(weight, price, 4)) } ``` +Javascript: +```Javascript +// 先遍历物品,再遍历背包容量 +function test_completePack1() { + let weight = [1, 3, 5] + let value = [15, 20, 30] + let bagWeight = 4 + let dp = new Array(bagWeight + 1).fill(0) + for(let i = 0; i <= weight.length; i++) { + for(let j = weight[i]; j <= bagWeight; j++) { + dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]) + } + } + console.log(dp) +} +// 先遍历背包容量,再遍历物品 +function test_completePack2() { + let weight = [1, 3, 5] + let value = [15, 20, 30] + let bagWeight = 4 + let dp = new Array(bagWeight + 1).fill(0) + for(let j = 0; j <= bagWeight; j++) { + for(let i = 0; i < weight.length; i++) { + if (j >= weight[i]) { + dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]) + } + } + } + console.log(2, dp); +} +``` -----------------------