Java教程

01背包+完全背包

本文主要是介绍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背包+完全背包的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!