当前位置:网站首页>tag动态规划-刷题预备知识-2. 0-1背包理论基础和二维数组解法模板
tag动态规划-刷题预备知识-2. 0-1背包理论基础和二维数组解法模板
2022-06-26 18:01:00 【菜菜的大数据开发之路】
面试常考察的背包问题

在看下面之前, 有必要通过一篇文章, 来熟悉背包问题填表过程: [点我](https://www.yuque.com/docs/share/2fbdf1a7-1499-4696-ab71-1df56240d2d1?# 《动态规划-背包问题》)
一, 0-1背包问题
1. 确定dp数组以及下标的含义
dp[i][j], 其中i代表的是物品, j指代的是背包的容量
如dp[i - 1][j] 表示从编号为
0~i-1的物品中任意选择, 放入到容量为j的背包, 价值总和dp[i -1][j] 最大为多少。

2. 确定递推公式

3. dp数组如何初始化

4. 确定遍历顺序

5. 举例推导dp数组

A. 二维数组的0-1背包模板
[代码实现]
public static void main(String[] args) {
int[] weight = {
1, 3, 4};
int[] value = {
15, 20, 30};
int bagsize = 4;
testweightbagproblem(weight, value, bagsize);
}
public static void testweightbagproblem(int[] weight, int[] value, int bagsize){
int wlen = weight.length, value0 = 0;
//定义dp数组:dp[i][j]表示背包容量为j时,前i个物品能获得的最大价值
int[][] dp = new int[wlen + 1][bagsize + 1];
//初始化:背包容量为0时,能获得的价值都为0
for (int i = 0; i <= wlen; i++){
dp[i][0] = value0;
}
//遍历顺序:先遍历物品,再遍历背包容量
for (int i = 1; i <= wlen; i++){
for (int j = 1; j <= bagsize; j++){
if (j < weight[i - 1]){
dp[i][j] = dp[i - 1][j];
}else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]);
}
}
}
//打印dp数组
for (int i = 0; i <= wlen; i++){
for (int j = 0; j <= bagsize; j++){
System.out.print(dp[i][j] + " ");
}
System.out.print("\n");
}
}
边栏推荐
- 用redis做用户访问数据统计HyperLogLog及Bitmap高级数据类型
- 在国金证券开户怎么样?开户安全吗?
- Detailed explanation of dos and attack methods
- Plt How to keep show() not closed
- Applet setting button sharing function
- Use FST JSON to automatically generate faster JSON serialization methods
- 如何将应用加入到deviceidle 白名单?
- Map and filter methods for processing scarce arrays
- 同花顺开户怎么样安全吗?怎么炒股开户
- 二分查找-2
猜你喜欢

【代码随想录-动态规划】T583、两个字符串的删除操作

Digital signature standard (DSS)

Number of solutions for knapsack problem

pycharm的plt.show()如何保持不关闭

mysql Add column 失败 因为之前有数据,不是默认null 不行

牛客网:设计LRU缓存结构 设计LFU缓存结构

transforms. The input of randomcrop() can only be PIL image, not tensor

深层次安全定义剖析及加密技术

Vue--vuerouter cache routing component

无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!
随机推荐
在国金证券开户怎么样?保障安全吗?
Case study of row lock and isolation level
How does Guosen Securities open an account? Is it safe to open a stock account through the link
分页查询、JOIN关联查询优化
halcon之区域:多种区域(Region)特征(5)
Properties file garbled
IDEA收藏代码、快速打开favorites收藏窗口
The difference between round and truncate in SQL (round or truncate)
Li Kou daily question - day 28 -566 Reshape matrix
决策树与随机森林
Map and filter methods for processing scarce arrays
ZCMU--1367: Data Structure
Several key points in divorce agreement
请指教同花顺开户选选择哪家券商比较好?现在在线开户安全么?
RSA encryption and decryption details
[code Capriccio - dynamic planning] t583. Deleting two strings
Solve the problem that each letter occupies a space in pycharm
数字签名论述及生成与优点分析
LeetCode——226. 翻轉二叉樹(BFS)
Leetcode HOT100 (22--- bracket generation)