vector<int> weight = {1, 3, 4};
vector<int> value = {15, 20, 30};
int bagWeight = 4;
// 01背包 如果先遍历背包 后遍历物品 那就是每个包只会装一个物品
for(int j = bagWeight; j >= 0; j--) {
for(int i = 0; i < weight.size(); i++) { // 遍历物品
// 遍历背包容量
if (j>=weight[i])
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
for (auto i : dp) cout << i << " ";
cout << endl;
}
上面的dp
0 0 0 0 30
0 0 0 20 30
0 0 15 20 30
0 15 15 20 30
0 15 15 20 30
完全背包的排列和组合的区别
https://programmercarl.com/0518.零钱兑换II.html#思路
class Solution {
public:
vector<int> coins= {1, 2, 5};
int amount = 5;
int change(int amount, vector<int>& coins) {
vector<int> dp(amount + 1, 0);
dp[0] = 1;
for (int i = 0; i < coins.size(); i++) { // 遍历物品
for (int j = coins[i]; j <= amount; j++) { // 遍历背包
dp[j] += dp[j - coins[i]];
}
}
return dp[amount];
}
};
上面是组合, dp是
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 1 0 0
1 1 1 1 1 0
1 1 1 1 1 1
1 1 2 1 1 1
1 1 2 2 1 1
1 1 2 2 3 1
1 1 2 2 3 3
1 1 2 2 3 4
class Solution {
public:
vector<int> coins= {1, 2, 5};
int amount = 5;
int change(int amount, vector<int>& coins) {
vector<int> dp(amount + 1, 0);
dp[0] = 1;
for (int j = 0; j <= amount; j++) { // 遍历背包容量
for (int i = 0; i < coins.size(); i++) { // 遍历物品
if (j - coins[i] >= 0) {
dp[j] += dp[j - coins[i]];
for (auto i : dp) cout << i << " ";
cout << endl;
}
}
}
return dp[amount];
}
};
上面是排列,dp是
1 1 0 0 0 0
1 1 1 0 0 0
1 1 2 0 0 0
1 1 2 2 0 0
1 1 2 3 0 0
1 1 2 3 3 0
1 1 2 3 5 0
1 1 2 3 5 5
1 1 2 3 5 8
1 1 2 3 5 9