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(); +``` + -----------------------