当前位置:网站首页>Dynamic planning 111
Dynamic planning 111
2022-06-26 19:54:00 【Jiangjiangchun】
Basic questions
- knapsack problem ( Restricted fetch set , Seeking value or variety )
- raid homes and plunder houses
- Stock issues
- Subsequence problem
Basic solution
- dp Array , And the meaning of subscript
- The recursive formula
- dp Array initialization
- traversal order ( One dimensional array layer , Two-dimensional array two layers )
If you find the combination number, it's the outer layer for Loop through items , Inner layer for Traverse the backpack .
If you find the permutation number, it's the outer layer for Traverse the backpack , Inner layer for Loop through items .
if 01 knapsack , From the back to the front , Otherwise, from front to back
- Print array (debug)
Ideas :
The key is to think from the bottom up
First consider step ,
For example, the backpack problem , The steps are to put items one by one , How to put items is the optimal solution . There are two steps for each item , Don't put . Observe the overall situation and decide whether to put it or not .( Step back from your head to see if you want to put )
Another example is going up the steps , Step is step , Taking a few steps is the optimal solution , You can take one or two steps at a time . Observe the overall situation and decide whether to take one step or two .( Step back from your head , Is it one-step optimal or two-step optimal each time )
Every step-by-step problem , The next state has a problem that depends on the previous state. Consider using dynamic programming . Start with the last step , Imagine what operations are required for the state from the last step to the end
The value of dynamic programming array must be the answer
knapsack problem ( Seeking value )
It is a set of values with limits and values . The capacity of the backpack and the weight of the items constitute a limitation , The value of the goods is the value .
Two dimensional writing :

// 1 dp Array subscript and its meaning
// dp[i][j]
//i: from 0 -i Item No j: Backpack Capacity
//ij: from 0-i Take whatever you like , Put in j The greatest value in
// 2 The recursive formula
// dp[i][j]=max(dp[i-1][j],dp[i-1][j-w]+value)
// 3 dp Array initialization
// Physical truth
// 4 traversal order
// First pack your stuff
//
function bagProblem(weight,value,volume){
let count=weight.size+1
// 1 Definition dp
const dp=[]
// 3 initialization dp Array
for (let j = volume; j >= weight[0]; j--) {
dp[0][j] = dp[0][j - weight[0]] + value[0];
}
// 4 traversal order
for(let i=1;i<weight.length;i++){
for(let j=0;j<=volume;j++){
if(j<weight[i]){
dp[i][j]=dp[i-1][j]
}else{
// 2 The recursive formula
dp[i][j]=max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
}
}
}
}Compress , One dimensional writing
From the picture above, we can get dp[i][j] Partly by dp[i-1][j] Copy it , Space can be omitted completely , Replace with a one-dimensional array
1、dp Definition
In one dimension dp Array ,dp[j] Express : Capacity of j The backpack , The value of the items carried can be up to dp[j].
2、 The recursive formula
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
here dp[j] There are two choices , One is to take yourself dp[j], One is to take dp[j - weight[i]] + value[i], Specify the maximum , After all, it's for maximum value ,
3、dp Array initialization
Initialize to 0
4、 traversal order
Cycle back and forth , Each acquisition state will not coincide with the previous acquisition state , So each item can only be taken once .
For two dimensions dp,dp[i][j] All through the upper layer, that is dp[i - 1][j] Come by calculation , On this floor dp[i][j] Not covered !
for(int i = 0; i < weight.size(); i++) { // Traverse the items
for(int j = bagWeight; j >= weight[i]; j--) { // Traverse the backpack capacity
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
// 1 dp Array subscript and its meaning
// dp[j]: Capacity of j The greatest value of time
//j: Capacity
// 2 The recursive formula
// dp[j]=max(dp[j],dp[j-w[i]]+value)
// there dp[j] In fact, it is a copy of the upper layer in a two-dimensional array , That is, the value of the previous item when it is not put
// 3 dp Array initialization
// All for 0
// 4 traversal order
// First pack your stuff
// Traverse the knapsack in reverse order , Prevent the upper state from being overwritten
function bagProblem(weight,value,volume){
let count=weight.size
// 1 Definition dp
const dp=[]
// 3 initialization dp Array
//
for(let i=0;i<volume;i++){
dp[i]=0
}
// 4 traversal order
for(let i=0;i<weight.length;i++){
// ps: Greater than weight, Less than weight You can't directly put it in and inherit the state of the previous level ( Not put directly )
for(let j=volume;j>=weight[i];j--){
// 2 Recursive formula
dp[j]=max(dp[j],dp[j-weight[i]]+value[i])
}
}
}Full backpack problem
Combination question
Topic link :https://leetcode-cn.com/problems/target-sum/
difficulty : secondary
Given an array of nonnegative integers ,a1, a2, ..., an, And a target number ,S. Now you have two symbols + and -. For any integer in the array , You can go from + or - Select a symbol to add to the front .
Return can make the final array and the target number S Of all methods to add symbols .
Limit :
left = (target + sum)/2 .
step
determine dp The meaning of arrays and subscripts
dp[j] Express : fill j( Include j) Such a large volume bag , Yes dp[i] Methods
In fact, you can also use two-dimensional dp Array to solve the problem ,dp[i][j]: Use Subscript to be [0, i] Of nums[i] Can fill up j( Include j) Such a large bag , Yes dp[i][j] Methods .
2、 The recursive formula
Don't consider nums[i] Under the circumstances , The filling capacity is j - nums[i] The backpack , Yes dp[j - nums[i]] Medium method .
So just get nums[i] Words , manage to put together dp[j] There is dp[j - nums[i]] Methods .
For example ,nums[i] = 2:dp[3], The capacity of the filled backpack is 3 Words , Yes dp[3] Methods .
Then you just need to get one 2(nums[i]), Yes dp[3] Method can aggregate a capacity of 3 The backpack , Correspondingly, there are many ways to gather the capacity of 5 The backpack .
So you need to take These methods add up ,dp[i] += dp[j - nums[j]
3、dp How to initialize an array
As can be seen from the recursive formula , At initialization time dp[0] Be sure to initialize to 1, because dp[0] Is the origin of all recursive results in the formula , If dp[0] yes 0 Words , The recursive result will be 0.
dp[0] = 1, It's also easy to explain in theory , The full capacity is 0 The backpack , Yes 1 Methods , It's just pretend 0 Item .
dp[j] The values corresponding to other subscripts should be initialized to 0, It can also be seen from the recursive formula ,dp[j] Make sure it's 0 The initial value of the , In order to correctly by dp[j - nums[i]] derived .
4、 traversal order
01 Knapsack problem dp The traversal ,nums Put it in the outer loop ,target Cycle, , And the internal circulation is reversed .
Recurrence formulas of several knapsacks
Ask if you can fill your backpack ( Or how much at most ):dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]); , The corresponding topics are as follows :
There are several ways to fill a backpack :dp[j] += dp[j - nums[i]] , The corresponding topics are as follows :
Ask if the back package is full of maximum value :dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); , The corresponding topics are as follows :
Ask the minimum number of all items in a full backpack :dp[j] = min(dp[j - coins[i]] + 1, dp[j]); , The corresponding topics are as follows :
raid homes and plunder houses
边栏推荐
- To: Apple CEO Cook: great ideas come from constantly rejecting the status quo
- Redis single sign on system + voting system
- Preliminary analysis of serial port printing and stack for arm bare board debugging
- Button how to dynamically set drawablebottom (setcomposunddrawables is invalid)
- 项目实战六:分布式事务-Seata
- Tiktok practice ~ sharing module ~ copy short video link
- Current limiting design and Implementation
- Super VRT
- 30. 串联所有单词的子串
- 股票开户的具体步骤是什么?网上开户安全吗?
猜你喜欢

The successfully resolved idea cannot use the log normally after referencing Lombok's @slf4j

mysql的充值问题

Arduino UNO + DS1302利用31字节静态RAM存储数据并串口打印

黑客用机器学习发动攻击的九种方法

Refresh the strong pointer assignment problem in the HP-UX system of Sanguan

Guomingyu: Apple's AR / MR head mounted display is the most complicated product in its history and will be released in January 2023

Arduino uno + DS1302 uses 31 byte static RAM to store data and print through serial port

阿里云个人镜像仓库日常基本使用

Feign remote call

Unit test of boot
随机推荐
Arduino UNO + DS1302利用31字节静态RAM存储数据并串口打印
Logstash安装及使用
Review of watermelon book (VII): Bayesian classifier (manual push + code demo)
8VC Venture Cup 2017 - Final Round C. Nikita and stack
论数据库的传统与未来之争之溯源溯本----AWS系列专栏
抖音实战~首页视频~下拉刷新
Pinda general permission system (day 1~day 2)
关于Qt数据库开发的一些冷知识
stm32和电机开发(直流有刷电机和步进电机)
西瓜书重温(七): 贝叶斯分类器(手推+代码demo)
网上办理中金财富开户安全吗?
C primer plus学习笔记 —— 3、字符的IO(输入/输出)
To: Apple CEO Cook: great ideas come from constantly rejecting the status quo
两个文件 合并为第三个文件 。
超分之VRT
Chain game development finished product source code chain game system development details
[MySQL series] collection of common working SQL (continuous update)
Project practice 5: build elk log collection system
Tiktok practice ~ sharing module ~ copy short video link
自己创建一个时间拦截器