topic:
There are 4 items and a backpack with a capacity of 7. You can choose any number of items for each item. The value of the i-th item is value[i], and its weight is weight[i]. Solving: which items to choose and put into the backpack , the value of these items can be maximized, and the sum of the volumes does not exceed the backpack capacity.
answer:
We draw the state transition equation by drawing:
Abstract the process to get the code as follows:
#include <bits/stdc++.h>
using namespace std;
int dp[100][100];
int main() {
int number = 4; //物品数量
int capacity = 7; //背包容量
int weight[number] = {1, 3, 4, 5}; //物品重量
int value[number] = {1, 4, 5, 7}; //物品价值
for (int i = 0; i < number; i++) {
for (int j = 0; j <= capacity; j++) {
//判断当前背包容量是否满足当前物品重量
if (j >= weight[i]) {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); //状态转移方程
}else{
dp[i][j] = dp[i - 1][j];
}
cout << dp[i][j] << " ";
}
cout << endl;
}
return 0;
}