01背包+完全背包
作者:互联网
01背包
1 void test_1_wei_bag_problem() { 2 vector<int> weight = {1, 3, 4}; 3 vector<int> value = {15, 20, 30}; 4 int bagWeight = 4; 5 6 // 初始化 7 vector<int> dp(bagWeight + 1, 0); 8 for(int i = 0; i < weight.size(); i++) { // 遍历物品 9 for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量 10 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); 11 } 12 } 13 cout << dp[bagWeight] << endl; 14 } 15 16 int main() { 17 test_1_wei_bag_problem(); 18 }
完全背包
1 // 先遍历物品,在遍历背包 2 void test_CompletePack() { 3 vector<int> weight = {1, 3, 4}; 4 vector<int> value = {15, 20, 30}; 5 int bagWeight = 4; 6 vector<int> dp(bagWeight + 1, 0); 7 for(int i = 0; i < weight.size(); i++) { // 遍历物品 8 for(int j = weight[i]; j <= bagWeight; j++) { // 遍历背包容量 9 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); 10 } 11 } 12 cout << dp[bagWeight] << endl; 13 } 14 int main() { 15 test_CompletePack(); 16 }
标签:背包,01,weight,int,bagWeight,完全,vector,遍历,dp 来源: https://www.cnblogs.com/yuhong1103/p/14799365.html