From f75acf5b896d78b5b124b7c6b3713a75a4206acc Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Tue, 29 Jun 2021 14:22:56 +0800 Subject: [PATCH] =?UTF-8?q?0-1=E8=83=8C=E5=8C=85javascript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 46 ++++++++++++++++++++++++ problems/背包理论基础01背包-2.md | 23 ++++++++++++ 2 files changed, 69 insertions(+) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 3cbfb347..85bc7e42 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -380,6 +380,52 @@ 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]; + } + } + } + +// 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]]); + } + } + return dp[size]; +} + + +function test () { + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); +} + +test(); +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 48275908..36856cd6 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -294,6 +294,29 @@ func main() { } ``` +javaScript: + +```js + +function testWeightBagProblem(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]]); + } + } + return dp[size]; +} + + +function test () { + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); +} + +test(); +``` + -----------------------