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 5440c3d

Browse files
添加(背包理论基础01背包-1.md):增加typescript版本
1 parent 6877683 commit 5440c3d

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
@@ -423,5 +423,47 @@ function test () {
423423
test();
424424
```
425425

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

0 commit comments

Comments
(0)

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