当前位置:网站首页>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");
}
}
边栏推荐
猜你喜欢

Binary search-2

padding百分比操作

9、智慧交通项目(2)

数字签名标准(DSS)

VSCode使用 - Remote-SSH 配置说明

Number of solutions for knapsack problem

Applet setting button sharing function

Case study of row lock and isolation level

清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!

Halcon's region: features of multiple regions (5)
随机推荐
数据加密标准(DES)概念及工作原理
ZCMU--1367: Data Structure
A little experience of next (ITER (dataloader))
How about opening an account at Guojin securities? Is it safe to open an account?
数据加密标准DES安全性
无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!
接水面试题
wechat_微信小程序中解决navigator进行页面跳转并传递参数问题
[ten thousand words summary] starting from the end, analyze in detail how to fill in the college entrance examination volunteers
决策树与随机森林
IDEA收藏代码、快速打开favorites收藏窗口
Padding percentage operation
DoS及攻擊方法詳解
vutils. make_ A little experience of grid () in relation to black and white images
离婚协议中的几个重点
Detailed explanation of asymmetric cryptosystem
How pycharm modifies multiline annotation shortcuts
Synchronized description of concurrency
How to add an application to the deviceidle whitelist?
【QNX】命令