Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 42c5fa7

Browse files
Merge pull request youngyangyang04#1277 from xiaofei-2020/dp11
添加(背包理论基础01背包-1.md):增加typescript版本
2 parents d47cbeb + 5440c3d commit 42c5fa7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎problems/背包理论基础01背包-1.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,5 +432,47 @@ function test () {
432432
test();
433433
```
434434

435+
### TypeScript
436+
437+
```typescript
438+
function testWeightBagProblem(
439+
weight: number[],
440+
value: number[],
441+
size: number
442+
): number {
443+
/**
444+
* dp[i][j]: 前i个物品,背包容量为j,能获得的最大价值
445+
* dp[0][*]: u=weight[0],u之前为0,u之后(含u)为value[0]
446+
* dp[*][0]: 0
447+
* ...
448+
* dp[i][j]: max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]);
449+
*/
450+
const goodsNum: number = weight.length;
451+
const dp: number[][] = new Array(goodsNum)
452+
.fill(0)
453+
.map((_) => new Array(size + 1).fill(0));
454+
for (let i = weight[0]; i <= size; i++) {
455+
dp[0][i] = value[0];
456+
}
457+
for (let i = 1; i < goodsNum; i++) {
458+
for (let j = 1; j <= size; j++) {
459+
if (j < weight[i]) {
460+
dp[i][j] = dp[i - 1][j];
461+
} else {
462+
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
463+
}
464+
}
465+
}
466+
return dp[goodsNum - 1][size];
467+
}
468+
// test
469+
const weight = [1, 3, 4];
470+
const value = [15, 20, 30];
471+
const size = 4;
472+
console.log(testWeightBagProblem(weight, value, size));
473+
```
474+
475+
476+
435477
-----------------------
436478
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /