From 5627d4ba8605f35b8d63cf4af363c64d721f69a3 Mon Sep 17 00:00:00 2001 From: Jamcy123 <1219502823@qq.com> Date: Thu, 12 May 2022 16:04:42 +0800 Subject: [PATCH] =?UTF-8?q?=E8=83=8C=E5=8C=85=E7=90=86=E8=AE=BA=E5=9F=BA?= =?UTF-8?q?=E7=A1=8001=E8=83=8C=E5=8C=85-1=20js=20=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 51 +++++++++--------------- 1 file changed, 19 insertions(+), 32 deletions(-) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index fe940b4c..e833ea80 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -380,44 +380,31 @@ func main() { ### javascript ```js -function testweightbagproblem (wight, value, size) { - const len = wight.length, - dp = array.from({length: len + 1}).map( - () => array(size + 1).fill(0) - ); - - for(let i = 1; i <= len; i++) { - for(let j = 0; j <= size; j++) { - if(wight[i - 1] <= j) { - dp[i][j] = math.max( - dp[i - 1][j], - value[i - 1] + dp[i - 1][j - wight[i - 1]] - ) - } else { - dp[i][j] = dp[i - 1][j]; - } +function testWeightBagProblem (weight, value, size) { + // 定义 dp 数组 + const len = weight.length, + dp = Array(len).fill().map(() => Array(size + 1).fill(0)); + + // 初始化 + for(let j = weight[0]; j <= size; j++) { + dp[0][j] = value[0]; } - } -// console.table(dp); - - return dp[len][size]; -} - -function testWeightBagProblem2 (wight, value, size) { - const len = wight.length, - dp = Array(size + 1).fill(0); - for(let i = 1; i <= len; i++) { - for(let j = size; j >= wight[i - 1]; j--) { - dp[j] = Math.max(dp[j], value[i - 1] + dp[j - wight[i - 1]]); + // weight 数组的长度len 就是物品个数 + for(let i = 1; i < len; i++) { // 遍历物品 + for(let j = 0; j <= size; j++) { // 遍历背包容量 + if(j < weight[i]) dp[i][j] = dp[i - 1][j]; + else dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); + } } - } - return dp[size]; -} + console.table(dp) + + return dp[len - 1][size]; +} function test () { - console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); } test();