卡码网 52. 携带研究材料
链接
#include <iostream>
#include <vector>
using namespace std;int knapsack(int w, vector<int>& weight, vector<int>& value) {vector<int> dp(w + 1, 0);for(int i = 0; i < weight.size(); i++) {for(int j = weight[i]; j <= w; j++) {dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);}}return dp[w];
}int main() {int m = 0, n = 0;cin >> m >> n;vector<int> weight(m, 0);vector<int> value(m, 0);for(int i = 0; i < m; i++) {cin >> weight[i] >> value[i];}int res = knapsack(n, weight, value);cout << res << endl;
}
LeetCode 518. 零钱兑换II
链接
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];}
};
LeetCode 377. 组合总和IV
链接
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] && dp[j] < INT_MAX - dp[j - nums[i]]) {dp[j] += dp[j - nums[i]];}}}return dp[target];}
};
卡码网 57. 爬楼梯
链接
#include <iostream>
#include <vector>
using namespace std;// 完全背包,求排列
int completeKnapsack(int target, int m) {vector<int> dp(target + 1, 0);dp[0] = 1;for(int i = 1; i <= target; i++) {for(int j = 1; j <= m; j++) {if(i >= j) {dp[i] += dp[i - j]; }}}return dp[target];}int main() {int m, n;cin >> n >> m;int ret = completeKnapsack(n, m);cout << ret;
}