Skip to content

Commit

Permalink
Merge pull request youngyangyang04#451 from flames519/master
Browse files Browse the repository at this point in the history
背包问题
  • Loading branch information
youngyangyang04 authored Jul 1, 2021
2 parents 1097fb5 + 204c0c5 commit 0f38eb9
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
20 changes: 20 additions & 0 deletions problems/0416.分割等和子集.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,26 @@ class Solution:
Go:


javaScript:

```js
var canPartition = function(nums) {
const sum = (nums.reduce((p, v) => p + v));
if (sum & 1) return false;
const dp = Array(sum / 2 + 1).fill(0);
for(let i = 0; i < nums.length; i++) {
for(let j = sum / 2; j >= nums[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
if (dp[j] === sum / 2) {
return true;
}
}
}
return dp[sum / 2] === sum / 2;
};
```




-----------------------
Expand Down
46 changes: 46 additions & 0 deletions problems/背包理论基础01背包-1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 23 additions & 0 deletions problems/背包理论基础01背包-2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
```



-----------------------
Expand Down

0 comments on commit 0f38eb9

Please sign in to comment.