Merge branch 'master' into 背包理论基础01背包-1

This commit is contained in:
程序员Carl
2022-05-31 08:48:02 +08:00
committed by GitHub
87 changed files with 2863 additions and 267 deletions

View File

@@ -410,5 +410,95 @@ function test () {
test();
```
### C
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define ARR_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#define BAG_WEIGHT 4
void backPack(int* weights, int weightSize, int* costs, int costSize, int bagWeight) {
// 开辟dp数组
int dp[weightSize][bagWeight + 1];
memset(dp, 0, sizeof(int) * weightSize * (bagWeight + 1));
int i, j;
// 当背包容量大于物品0的重量时将物品0放入到背包中
for(j = weights[0]; j <= bagWeight; ++j) {
dp[0][j] = costs[0];
}
// 先遍历物品,再遍历重量
for(j = 1; j <= bagWeight; ++j) {
for(i = 1; i < weightSize; ++i) {
// 如果当前背包容量小于物品重量
if(j < weights[i])
// 背包物品的价值等于背包不放置当前物品时的价值
dp[i][j] = dp[i-1][j];
// 若背包当前重量可以放置物品
else
// 背包的价值等于放置该物品或不放置该物品的最大值
dp[i][j] = MAX(dp[i - 1][j], dp[i - 1][j - weights[i]] + costs[i]);
}
}
printf("%d\n", dp[weightSize - 1][bagWeight]);
}
int main(int argc, char* argv[]) {
int weights[] = {1, 3, 4};
int costs[] = {15, 20, 30};
backPack(weights, ARR_SIZE(weights), costs, ARR_SIZE(costs), BAG_WEIGHT);
return 0;
}
```
### TypeScript
```typescript
function testWeightBagProblem(
weight: number[],
value: number[],
size: number
): number {
/**
* dp[i][j]: 前i个物品背包容量为j能获得的最大价值
* dp[0][*]: u=weight[0],u之前为0u之后含u为value[0]
* dp[*][0]: 0
* ...
* dp[i][j]: max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]);
*/
const goodsNum: number = weight.length;
const dp: number[][] = new Array(goodsNum)
.fill(0)
.map((_) => new Array(size + 1).fill(0));
for (let i = weight[0]; i <= size; i++) {
dp[0][i] = value[0];
}
for (let i = 1; i < goodsNum; i++) {
for (let j = 1; j <= size; j++) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
}
}
}
return dp[goodsNum - 1][size];
}
// test
const weight = [1, 3, 4];
const value = [15, 20, 30];
const size = 4;
console.log(testWeightBagProblem(weight, value, size));
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>