Classic problem: if the number of items is n and the weight of the backpack is V, the time complexity is O (NV ).
The space complexity is O (V ).
However, if you want to get the final result of the selection, you need to record the intermediate results. The space complexity can only be O (NV ).
#include <iostream>using namespace std;int max(int a,int b) {return a>=b ? a : b;}int bag_use_one_array (const int weight[], const int value[], const int item_size, const int bag_weight) {int max_value[bag_weight+1];for (int i=0; i<=bag_weight; i++) {max_value[i] = 0;}for (int i=0; i<item_size; i++) {for (int w=bag_weight; w>=1; w--) {if (weight[i] <= w) {//max_value[w] = max(max_value[w], max_value[w-weight[i]]+value[i]);if ( max_value[w] >= max_value[w-weight[i]]+value[i]) {} else {max_value[w] = max_value[w-weight[i]]+value[i];}cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w] << endl;}}cout << endl;}cout << "max value is : " << max_value[bag_weight] << endl;cout << endl;return max_value[bag_weight];}int bag_get_best_choice (const int weight[], const int value[], const int item_size, const int bag_weight) {int max_value[bag_weight+1][item_size+1];for (int i=0; i<=bag_weight; i++) {max_value[i][0] = 0;}for (int j=0; j<=item_size; j++) {max_value[0][j] = 0;}for (int i=1; i<=item_size; i++) {for (int w=bag_weight; w>=1; w--) {if (weight[i-1] <= w) {if ( max_value[w][i-1] >= max_value[w-weight[i-1]][i-1]+value[i-1]) {max_value[w][i] = max_value[w][i-1];} else {max_value[w][i] = max_value[w-weight[i-1]][i-1]+value[i-1];}} else { max_value[w][i] = max_value[w][i-1];}cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w][i] << endl;}cout << endl;}cout << "max value is : " << max_value[bag_weight][item_size] << endl;cout << endl;int choice[item_size];int weight_choice = bag_weight;for (int i=item_size-1; i>=0; i--) {if (max_value[weight_choice][i+1] > max_value[weight_choice][i]) { choice[i]=1;weight_choice -= weight[i];} else { choice[i]=0;}}for (int i=0; i<item_size; i++) {cout << choice[i] << " ";}cout << endl;return max_value[bag_weight][item_size];}int main() {const int item_size = 5;const int bag_weight = 15; int weight[item_size] = {12,1,4,1,2};int value[item_size] = {4,2,10,1,2};//bag_use_one_array(weight, value, item_size, bag_weight);bag_get_best_choice(weight, value, item_size, bag_weight);return 0;}
This article is from the "New Home Tianyan prodigy" blog, please be sure to keep this source http://tianyanshentong.blog.51cto.com/3356396/1556397
01 backpack problem implementation source code