完全背包和01背包的区别就是是否可以重复使用,在代码上就是 j 的 for 循环从前向后遍历还是从后向前遍历
题目:52. 携带研究材料(第七期模拟笔试) (kamacoder.com)
#include<iostream>
#include<vector>
using namespace std;
int main() {
int N, V;
cin >> N >> V;
vector<int> wegiht(N, 0);
vector<int> val(N, 0);
for(int i = 0;i < N;i++) {
cin >> wegiht[i] >> val[i];
}
vector<int> dp(V + 1, 0);
for(int i = 0;i < N;i++) {
for(int j = wegiht[i];j <= V;j++) {
dp[j] = max(dp[j], dp[j - wegiht[i]] + val[i]);
}
}
cout << dp[V] << endl;
return 0;
}
题目2:518. 零钱兑换 II - 力扣(LeetCode)
先物品再背包是组合,先背包再物品是排列
class Solution {
public:
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];
}
};
题目3:377. 组合总和 Ⅳ - 力扣(LeetCode)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
for(int j = 0;j <= target;j++) {
for(int i = 0;i < nums.size();i++) {
if (j - nums[i] >= 0 && dp[j] < INT_MAX - dp[j - nums[i]]) {
dp[j] += dp[j - nums[i]];
}
}
for(int j = 0;j <= target;j++) {
cout << dp[j] << ",";
}
cout << "---------" << endl;
}
return dp[target];
}
};