当前位置:网站首页>Theory + practice will help you master the dynamic programming method
Theory + practice will help you master the dynamic programming method
2022-06-12 22:42:00 【InfoQ】
One 、 Basic concepts
The professional term is :
It's hard to understand , Let me explain to you :
Two 、 basic feature
1) Big problem decomposability
2) Sub problem solvability
3) Solution mergeability
4) The overlapping of subproblems
3、 ... and 、 Some misunderstandings
1. State transition equation
2. initialization
3. The boundary conditions
Four 、 The basic steps of dynamic programming
step1 decompose :
step2 State shift :
step3 Write code :
step4 Get the solution :
5、 ... and 、 Classical problems
Longest text substring
// Dynamic programming has two basic elements : Optimal substructure property and subproblem overlap property .
// Many answers write initialization and boundary conditions , Personally, I think you should distinguish what his purpose is .
// Many initialization and boundary conditions , Because the state transition equation , Is the solution of the subproblem that needs to be initialized , To avoid double counting , To put it bluntly, it is still a sub problem overlap and optimal sub structure problem .
// We should pay attention to the decomposition of overlapping subproblems of a problem and the decision analysis of state optimization .
// Their thinking :
// When calculating a string , If it has the same beginning and end characters , Is it a palindrome , It depends on whether the string after removing the head and tail is a palindrome string .
// If its first and last characters are not equal , Then it must not be a palindrome
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
// Special judgement
if (len < 2){
return s;
}
int maxLen = 1;
int begin = 0;
// 1. State definition
// dp[i][j] Express s[i...j] Is it a palindrome string , Now it means all 0, It's not a palindrome string
boolean[][] dp = new boolean[len][len];
char[] chars = s.toCharArray();
// 2. Calculation order of subproblems : First calculate the short string , Calculating long strings , At the same time, according to the obtained short string or calculation rules , You can get the solution of a long string .
// Be careful :s Indicates the element order of the calculation .
// 0 1 2 3 4
// 0 xx s1 s2 s4 s7
// 1 xx s3 s5 s8
// 2 xx s6 s9
// 3 xx s10
// 4 xx
// Why do you write that , Because you have to make sure that when you calculate an element , Through the state transition equation, we can get the dp[][].
// Rules for filling in the form : Fill in one column first , Fill in line by line , Ensure that when calculating an element , The upper left cell has been calculated
// Rules for filling in the form : One line from left to right, of course , This also ensures that when calculating an element , The upper left cell has been calculated
for (int j = 1;j < len;j++){
for (int i = 0; i < j; i++) {
// The beginning and end characters are not equal , It's not a palindrome string
if (chars[i] != chars[j]){
dp[i][j] = false;
}else {
// In the case of equality
// Because there are no characters left after the head and tail are removed , Or when there is one character left , It must be a palindrome string
if (j - i -1 <= 1){
dp[i][j] = true;
}else {
// Equal head and tail , There is more than in the middle 1 Elements , This is the time , We can't directly judge whether he is a palindrome , But we can judge by the state transition equation
// In fact, this is calculating s8 This element is , We can't judge dp[1][4] stay 1 and 4 When the bit elements are equal , Whether the whole string is a palindrome .
// So we have to go through s4 To judge ,s4 It's palindrome. ,s8 Namely .s4 No , that s8 It's not .
dp[i][j] = dp[i + 1][j - 1];
}
}
// as long as dp[i][j] == true establish , Express s[i...j] Is it a palindrome string
// At this time, the record palindrome length and starting position are updated
if (dp[i][j] && (j - i + 1 > maxLen)){
maxLen = j - i + 1;
begin = i;
}
}
}
// 3. initialization
// Many answers write this , This step , Let's think about , In fact, there is no need .
// Because the main diagonal , The value can be judged directly .
// And in the process of solving , Our state transition equation will not use this value . Because only the main diagonal will use these values .
// And the subproblem solution of a single element , We don't need .
// therefore , Even if I put this initialization after the calculation , Even directly remove , It doesn't affect the result at all . You can try it on your own
// for (int i = 0; i < len; i++) {
// dp[i][i] = true;
// }
// 4. Return value
return s.substring(begin,begin + maxLen);
}
}边栏推荐
- 【LeetCode】300. Longest ascending subsequence
- 【图像去噪】基于三边滤波器实现图像去噪附matlab代码
- [data analysis] data clustering and grouping based on kmeans, including Matlab source code
- Yyds dry inventory insider news: Series high-frequency interview questions, worth a visit!
- Yyds dry goods inventory solution Huawei machine test: weighing weight
- Research Report on water sports shoes industry - market status analysis and development prospect forecast
- [890. find and replace mode]
- Flutter series part: detailed explanation of GridView layout commonly used in flutter
- Database daily question --- day 10: combine two tables
- The shutter library recommends sizer to help you easily create a responsive UI
猜你喜欢

C language: how to give an alias to a global variable?
![[data analysis] data clustering and grouping based on kmeans, including Matlab source code](/img/76/deec6cf60c0d02e99ebc3e21d3b8a4.png)
[data analysis] data clustering and grouping based on kmeans, including Matlab source code

Qrcodejs2 QR code generation JS
![[Part 8] semaphore source code analysis and application details [key points]](/img/e2/05c08435d60564aaa1172d2d574675.jpg)
[Part 8] semaphore source code analysis and application details [key points]

The annual salary of 500000 is one line, and the annual salary of 1million is another line

Mysql case when then函数使用

【数据分析】基于 kmeans实现数据聚类分组含Matlab源码

年薪50万是一条线,年薪100万又是一条线…...

MySQL case when then function use

数据库每日一题---第10天:组合两个表
随机推荐
四元数简介
Modstartcms modular station building system v3.3.0 component function upgrade, event triggering enhancement
The annual salary of 500000 is one line, and the annual salary of 1million is another line
42岁大厂高管,给30岁-39岁人提个醒:这6个让你变强的习惯,要尽快养成
【LeetCode】103. 二叉树的锯齿形层序遍历
认识的几位清华同学都离职了……
[probability theory and mathematical statistics] final review: formula summary and simple examples (end)
Design a MySQL table for message queue to store message data
【数据分析】基于 kmeans实现数据聚类分组含Matlab源码
RAID disk array
同花顺股票账户开户安全吗
【LeetCode】103. Zigzag sequence traversal of binary tree
反走样/抗锯齿技术
認識的幾比特清華同學都離職了……
Design of traceid in the project
LeetCode —— 26. Remove duplicates from an ordered array
Analysis report on the "fourteenth five year plan" and the latest development trend of China's medical information industry from 2022 to 2028
Dix points de défense clés dans les exercices d'attaque et de défense détaillés
Alcohol detector based on 51 single chip microcomputer
JVM Basics - > how to troubleshoot JVM problems in your project