背包问题-LintCode
来源:互联网 发布:怎么禁用135端口 编辑:程序博客网 时间:2024/05/21 06:57
在n个物品中挑选若干物品装入背包,最多能装多满?假设背包的大小为m,每个物品的大小为A[i]
样例
如果有4个物品[2, 3, 5, 7]
如果背包的大小为11,可以选择[2, 3, 5]装入背包,最多可以装满10的空间。
如果背包的大小为12,可以选择[2, 3, 7]装入背包,最多可以装满12的空间。
函数需要返回最多能装满的空间大小。
思路:
两次循环,外部遍历数组A,内部反向遍历数组dp,若j即背包容量大于等于物品体积A[i],则取前i-1次循环求得的最大容量dp[j],和背包体积为j-A[i]时的最大容量dp[j-A[i]]与第i个物品体积A[i]之和即dp[j-A[i]]+A[i]的较大值,作为本次循环后的最大容量dp[i]。
#ifndef C92_H#define C92_H#include<iostream>#include<vector>#include<algorithm>using namespace std;class Solution {public: /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @return: The maximum size */ int backPack(int m, vector<int> A) { // write your code here if (A.empty()) return 0; vector<int> dp(m + 1, 0); for (int i = 0; i<A.size(); ++i) { for (int j = m; j >=1; --j) { if (j >= A[i]) { dp[j] = maxVal(dp[j - A[i]] + A[i], dp[j]); } } } return dp[m]; } int maxVal(int a, int b) { return a > b ? a : b; }};#endif
阅读全文
0 0
- LintCode-背包问题 II
- 【LintCode】Backpack 背包问题
- lintcode-背包问题-92
- LintCode : 背包问题 II
- LintCode :背包问题
- LintCode : 背包问题 II
- lintcode backpack 背包问题
- LintCode:背包问题
- LintCode:背包问题 II
- LintCode(M)背包问题
- LintCode:背包问题
- LintCode:01背包问题
- LintCode 62-背包问题
- LintCode 背包问题
- 背包问题-LintCode
- Lintcode 背包问题
- LintCode背包问题总结
- lintcode -- 背包问题
- 175. Combine Two Tables--left join
- (二)设置PDF纸张并在指定位置添加文字
- mysql 创建数据库字段类型
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料(Chapter 2)
- codeforces 822 C. Hacker, pack your bags!(思维+dp)
- 背包问题-LintCode
- Android butterknife view注入框架
- 正则表达式"\\s+"
- 24天学会设计模式------责任链模式
- BaseModel
- JavaScript事件委托的技术原理
- Scala JDBC 查询和更新MySQL
- Spring容器ApplicationContext实现和配置WebApplicationContext
- Eclipse中移除未使用的类引用的三种办法