【动态规划】01背包问题
作者:互联网
struct content { int weight; int value; content(int weight, int value) : weight(weight), value(value) {} }; /** *动态规划解决背包问题,使用滚动数组减少空间复杂度 * @param contents 物品 * @param bagWeight 背包的重量 * @return 能同时装进背包的物品的总价值的最大值 */ int BagProblemSolution(const vector<content> & contents, const int & bagWeight){ vector<int> dp(bagWeight + 1, 0); for(int i = 0; i < contents.size(); ++i) { for (int j = bagWeight; j >= contents[i].weight; --j) { dp[j] = max(dp[j], dp[j - contents[i].weight] + contents[i].value); } } return dp[bagWeight]; } int main() { //物品的重量和价值 vector<content> contents; contents.emplace_back(1,15); contents.emplace_back(3,20); contents.emplace_back(4,30); //背包的重量 int bagWeight = 4; cout << BagProblemSolution(contents, bagWeight) << endl; //输出35 return 0; }
标签:01,weight,int,bagWeight,value,背包,dp,动态,contents 来源: https://www.cnblogs.com/XiLu-H/p/16408847.html