0-1背包问题
来源:互联网 发布:英译汉软件免费下载 编辑:程序博客网 时间:2024/06/10 01:27
状态 &转移
状态:
状态转移:
解题代码
class Solution {private: vector<vector<int>> memo; // [0..index] 放进容量为C的背包的最大价值 int maxValue(const vector<int> &w, const vector<int> &v, int index, int C){ if (index < 0 || C <= 0)return 0; if (memo[index][C] != -1)return memo[index][C]; memo[index][C] = max(maxValue(w, v, index - 1, C), w[index] <= C ? v[index] + maxValue(w, v, index - 1, C - w[index]) : 0); return memo[index][C]; }public: // 动态规划 (优化,只用一维数组存储) int knapsack2(const vector<int> &w, const vector<int> &v, int C){ int n = w.size(); if (n == 0)return 0; // memo[i][j] : 考虑将[0..i]物品放进容积为j的背包最大价值 vector<int> memo(C + 1, -1); // 对基础问题进行设置,对[0,0]物品进行考虑,分别放进容量为[0..C]的背包的最大价值 for (int j = 0; j <= C; j++) memo[j] = (j >= w[0] ? v[0] : 0); for (int i = 1; i < n; i++){ for (int j = C; j >= w[i]; j--) memo[j] = max(memo[j], j >= w[i] ? v[i] + memo[j - w[i]] : 0); } return memo[C]; } // 动态规划 int knapsack1(const vector<int> &w, const vector<int> &v, int C){ int n = w.size(); if (n == 0)return 0; // memo[i][j] : 考虑将[0..i]物品放进容积为j的背包最大价值 memo = vector<vector<int>>(n, vector<int>(C + 1, -1)); // 对基础问题进行设置,对[0,0]物品进行考虑,分别放进容量为[0..C]的背包的最大价值 for (int j = 0; j <= C; j++) memo[0][j] = (j >= w[0] ? v[0] : 0); for (int i = 1; i < n; i++){ for (int j = 0; j <= C; j++) memo[i][j] = max(memo[i - 1][j], j >= w[i] ? v[i] + memo[i - 1][j - w[i]] : 0); } return memo[n-1][C]; } int knapsack(const vector<int> &w, const vector<int> &v, int C){ int n = w.size(); memo = vector<vector<int>>(n, vector<int>(C + 1, -1)); return maxValue(w, v, n - 1, C); } // 测试 void test(){ int weight[] = { 1, 2, 3 }; int value[] = { 6, 10, 12 }; vector<int> w(weight, weight + 3), v(value, value+3); cout << knapsack(w, v, 5) << endl; }};
阅读全文
0 0
- 背包问题(0-1背包、完全背包、多重背包)详解
- 背包问题和0-1背包问题
- 背包问题和0-1背包问题
- 背包问题系列--"0-1背包问题"
- 背包笔记-含0/1背包问题、完全背包问题、多重背包问题、二维背包问题、分组背包问题
- 【背包问题】背包问题之0-1背包、完全背包、多重背包
- 0-1背包问题
- 0/1背包问题
- 0,1背包问题
- 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- // 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- 0-1背包问题
- 0-1背包问题
- 0/1背包问题
- 辗转相余求最大公约数
- MAC 打开.bash_profile
- POJ
- java 按值调用 与 按引用(对象的引用,指针)调用、区分对象与对象引用
- Git 使用规范流程
- 0-1背包问题
- 2018今日头条内推笔试2
- hdu-6162
- Mysql查询性能优化的心得
- 《计算机视觉-一种现代方法(第2版)》读书笔记一:导论大纲
- angularjs bootstrap 购物车
- ImportError: No module named tensorflow
- JDBC中ResultSet结果集总结(三)
- hdu1242Rescue(dfs基础)