当前位置:网站首页>Introduction to dynamic planning I, BFS of queue (70.121.279.200)
Introduction to dynamic planning I, BFS of queue (70.121.279.200)
2022-07-02 15:48:00 【-Xiaoxiaobai-】
What is dynamic programming
Dynamic planning is to use historical data to avoid double counting , Historical data is saved in one-dimensional array or two-dimensional array .
Using dynamic programming to solve problems requires two basic steps :1. First define the array and clarify the meaning of the array , Assign initial value to array ,2. Then find the connection between the elements ( Dynamic transfer equation ) Finally, the result .
Example
Next, use three examples to get started with dynamic planning .
1. climb stairs

1. Define an array dp[ n ],dp[ n ] The value of represents walking to n There are several ways to order .
2. Assign initial value to , obviously dp[ 1 ] = 1, dp[ 2 ] = 2.
3. Look for connections between elements ( Dynamic transfer equation ), Easy to come by n>=3 After a dp [ n ] = dp[ n - 1 ] + dp[ n - 2 ]; Because I came to n Order can be determined by n - 1 Take one step at a time to reach , It can also be done by n - 2 Take two steps at a time to arrive .
int climbStairs(int n){
if(n == 1)return 1;
if(n == 2)return 2;
int dp[n + 1];
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i <= n; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}2. The best time to buy and sell stocks

This question is more suitable for traversing an array at one time , Record historical data changes with two variables , Use variables min Record until n God , The lowest selling price of the stock . Reuse gap Record with n Sell stocks at a price of days , The profits you can get , use tgap Record the maximum profit . to min,gap,tgap Assign initial value to 0, After traversing the array once tgap The stored data is the maximum profit .
#define max(a, b) a>b ? a : b
#define min(a, b) a<b ? a : b
int maxProfit(int* prices, int pricesSize){
int m = prices[0], gap = 0, tgap = 0;
for(int i = 0; i < pricesSize; i++){
m = min(m, prices[i]);
if(prices[i] > m){
gap = prices[i] - m;
tgap = max(gap, tgap);
}
}
return tgap;
}3. Complete square

1. Define an array dp[ n ], dp[ n ] The value of and is expressed as n The minimum number of complete squares of .
2. Assign initial value to , Give Way dp[ n ] = n( The worst , The factor is n individual 1).
3. Look for connections between elements ( Dynamic transfer equation ), Observe to get , There is an optimal connection between two continuous data , for example dp[ 5 ] = 2, that dp[ 6 ] It can be understood as dp[ 5 ]+dp[ 1 ] = 2 + 1 = 4. explain n The optimal solution of is related to the previous data . The connection between the two solutions is j*j, enumeration j = 1;j * j < i; j++; Yes dp[ i ] = min(dp[ i ], dp[ i - j * j ] + 1);
#define min(a, b) a<b ? a : b
int numSquares(int n){
int dp[n + 1];
for(int i = 0; i <= n; i++){
dp[i] = i;
for(int j = 1; j * j <= i; j++){
dp[i] = min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}Queued bfs
Number of Islands

- How to solve the problem : Sinking method , Every time a piece of land is found, the whole piece is sunk ( become 0).
- Specific ideas : Traversing a two-dimensional array , Find out 1 Back entry bfs, Sink the whole land in the function .
- skill :1. Create an array of directions dir[4][2] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1}} Find out 1 when ,for Cycle for four times to judge whether there is land in the upper, lower, left and right of this land , Others are listed .
2. Use Circular queue ,front The pointer is in front of rear Pointer after , For each front, Judge whether there is land up, down, left and right , One sank the land and then joined the team in this position ( Each cycle rear May move forward 0~3 position ), After joining the team front Move forward one bit , Repeat the above steps until front == rear The whole land .
int dir[4][2] = {
{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
typedef struct{
int x;
int y;
}node;
#define MAX 305
bool inside(int i, int j, int row, int col){
return (i >= 0)&&(j >= 0)&&(i < row)&&(j < col);
}
void bfs(char** grid, int i, int j, int gridSize, int colSize){
node* queue[MAX + 1];
node* cur = (node*)malloc(sizeof(node));
cur->x = i;
cur->y = j;
int front = 0, rear = 0;
queue[rear++] = cur;
while(front != rear){
cur = queue[front];
front = (front + 1) % MAX;
for(int k = 0; k < 4; k++){
int ox = cur->x + dir[k][0];
int oy = cur->y + dir[k][1];
if(inside(ox, oy, gridSize, colSize) && grid[ox][oy] == '1'){
grid[ox][oy] = '0';
node* next = (node*)malloc(sizeof(node));
next->x = ox;
next->y = oy;
queue[rear] = next;
rear = (rear + 1) % MAX;
}
}
}
}
int numIslands(char** grid, int gridSize, int* gridColSize){
int colSize = gridColSize[0], ans = 0;
for(int i = 0; i < gridSize; i++){
for(int j = 0; j < colSize; j++){
if(grid[i][j] == '1'){
ans++;
bfs(grid, i, j, gridSize, colSize);
}
}
}
return ans;
}边栏推荐
- Xpt2046 four wire resistive touch screen
- Use ffmpeg command line to push UDP and RTP streams (H264 and TS), and ffplay receives
- 6092. Replace elements in the array
- /Bin/ld: cannot find -lxml2
- /bin/ld: 找不到 -lcrypto
- /bin/ld: 找不到 -lxml2
- Deux séquences ergodiques connues pour construire des arbres binaires
- Two traversal sequences are known to construct binary trees
- Pyinstaller打包exe附带图片的方法
- Target detection - make your own deep learning target detection data set with labelimg
猜你喜欢

Thoroughly understand browser strong cache and negotiation cache

(Video + graphic) machine learning introduction series - Chapter 5 machine learning practice

全是精华的模电专题复习资料:基本放大电路知识点

PTA 天梯赛习题集 L2-001 城市间紧急救援
![[development environment] install the Chinese language pack for the 2013 version of visual studio community (install test agents 2013 | install visual studio 2013 simplified Chinese)](/img/cf/38e4035c3b318814672f21c8a42618.jpg)
[development environment] install the Chinese language pack for the 2013 version of visual studio community (install test agents 2013 | install visual studio 2013 simplified Chinese)
![[leetcode] 1905 statistics sub Island](/img/82/d2f7b829f5beb7f9f1eabe8d101ecb.png)
[leetcode] 1905 statistics sub Island
![[leetcode] 1254 - count the number of closed Islands](/img/84/f888ae0e164951cd9623fb3bf4a984.png)
[leetcode] 1254 - count the number of closed Islands

XPT2046 四线电阻式触摸屏

智联招聘的基于 Nebula Graph 的推荐实践分享

【LeetCode】1254-统计封闭岛屿的数量
随机推荐
[leetcode] 1162 map analysis
6096. Success logarithm of spells and potions
XPT2046 四线电阻式触摸屏
【idea】推荐一个idea翻译插件:Translation「建议收藏」
Use ffmpeg command line to push UDP and RTP streams (H264 and TS), and ffplay receives
[leetcode] 283 move zero
【LeetCode】200-岛屿数量
[leetcode] 977 square of ordered array
SQL FOREIGN KEY
已知兩種遍曆序列構造二叉樹
《大学“电路分析基础”课程实验合集.实验六》丨典型信号的观察与测量
【LeetCode】417-太平洋大西洋水流问题
二叉树前,中,后序遍历
/bin/ld: 找不到 -lpam
Comparison between rstan Bayesian regression model and standard linear regression model of R language MCMC
/bin/ld: 找不到 -lcrypto
Analysis of the difference between array and linked list
Loss function and positive and negative sample allocation: Yolo series
Xpt2046 four wire resistive touch screen
[leetcode] 344 reverse string