当前位置:网站首页>Hot 100 dynamic programming
Hot 100 dynamic programming
2022-07-24 00:56:00 【wzf6667】
- Maximum subarray and
Give you an array of integers nums , Please find a continuous subarray with the largest sum ( A subarray contains at least one element ), Return to its maximum and .
Subarray Is a continuous part of the array .
Example 1:
Input :nums = [-2,1,-3,4,-1,2,1,-5,4]
Output :6
explain : Continuous subarray [4,-1,2,1] And the biggest , by 6 .
dp[] What is loaded in is the value of the current largest continuous subsequence , If the previous value is negative , Is the current dp[i] Load nums[i], Load on the contrary dp[i-1]+nums[i]
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++){
if(dp[i-1] > 0){
dp[i] = dp[i-1] + nums[i];
}
else{
dp[i] = nums[i];
}
}
for(int i = 0; i < dp.length; i++){
max = Math.max(dp[i],max);
}
return max;
}
}
- Different paths
A robot is in a m x n The top left corner of the grid ( The starting point is marked as “Start” ).
The robot can only move down or right one step at a time . The robot tries to reach the bottom right corner of the grid ( In the figure below, it is marked as “Finish” ).
Ask how many different paths there are in total ?
dp[i][j] Express i That's ok j How many paths does the column have at most
dp[i][j] = dp[i-1][j] + dp[i][j-1]
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for(int i = 0; i < m; i++){
dp[i][0] = 1;
}
for(int i = 0; i < n; i++){
dp[0][i] = 1;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}
- Word splitting
Give you a string s And a list of strings wordDict As a dictionary . Please judge whether you can use the words in the dictionary to splice s .
Be careful : It is not required to use all the words in the dictionary , And the words in the dictionary can be reused .
For example, by the word applepen list=[apple,pen]
dp[i] To i Whether letters can form words
that ,dp[i] = dp[j] && check(j-i),dp[j] To j Can words be formed ,check From j To i Whether it appears in list in
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++){
for(int j = 0; j < i; j++){
dp[i] = dp[j] && wordDict.contains(s.substring(j,i));
if(dp[i] == true){
break;
}
}
}
return dp[s.length()];
}
}
- raid homes and plunder houses
You are a professional thief , Plan to steal houses along the street . There is a certain amount of cash in every room , The only restriction on your theft is that adjacent houses are equipped with interconnected anti-theft systems , If two adjacent houses are broken into by thieves on the same night , The system will automatically alarm .
Given an array of non negative integers representing the storage amount of each house , Count you Without triggering the alarm , The maximum amount that can be stolen overnight .
Example 1:
Input :[1,2,3,1]
Output :4
explain : Steal 1 House No ( amount of money = 1) , And then steal 3 House No ( amount of money = 3).
Maximum amount stolen = 1 + 3 = 4 .
State transition equation : dp[i] = Max(dp[i-2]+nums[i],dp[i-1])
- Complete square
Give you an integer n , return And for n The minimum number of complete squares of .
Complete square It's an integer , Its value is equal to the square of another integer ; let me put it another way , Its value is equal to the product of the self multiplication of an integer . for example ,1、4、9 and 16 They're all perfect squares , and 3 and 11 No .
Example 1:
Input :n = 12
Output :3
explain :12 = 4 + 4 + 4
State transition equation :dp[i] = Math.min(dp[i],dp[i-jj]+1);
dp[i] Express i The least square required , Traverse than i All small squares ,dp[i-jj]+1 Indicates if j Is the square number , The remaining number needs several squares . At the same time, add 1 Indicates that j.
- The longest increasing subsequence
Give you an array of integers nums , Find the length of the longest strictly increasing subsequence .
Subsequence Is a sequence derived from an array , Delete ( Or do not delete ) Elements in an array without changing the order of the rest . for example ,[3,6,2,7] It's an array [0,3,1,6,2,2,7] The subsequence .
Example 1:
Input :nums = [10,9,2,5,3,7,101,18]
Output :4
explain : The longest increasing subsequence is [2,3,7,101], So the length is 4 .
dp[i] It's loaded with i For the longest increment subsequence at the end , Just find i Before , Than i Small number j, Compare dp[j]+1 Size , Find the maximum , Can be calculated dp[i] The maximum of . Finally from the dp Find the maximum in
dp[i] = Math.max(dp[i],dp[j]+1);
- raid homes and plunder houses III
The thief found a new area to steal . There is only one entrance to the area , We call it root .
except root outside , Each house has and only has one “ Father “ The house is connected to it . After some reconnaissance , The clever thief realized that “ All the houses in this place are arranged like a binary tree ”. If Two directly connected houses were robbed the same night , The house will alarm automatically .
Given a binary tree root . return Without triggering the alarm , The maximum amount a thief can steal .
Depth-first search , Return value [i,j] i Indicates the maximum value of the selected current node ,j Indicates that the maximum value of the current node is not selected
result[0] = root.val + left[1] + right[1];
result[1] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
It should be noted that , Do not select the value of the current node , Need comparison left,right,0 and 1 Size , There may be two consecutive points that are not selected .
- Bit count
Give you an integer n , about 0 <= i <= n Each of the i , Calculate its binary representation 1 The number of , Returns a length of n + 1 Array of ans As the answer .
Example 1:
Input :n = 2
Output :[0,1,1]
explain :
0 --> 0
1 --> 1
2 --> 10
n&(n-1) You can put n Last digit of 1 become 0, thus , as long as n>0, You can always calculate how many there are in this way 0
class Solution {
public int[] countBits(int n) {
int[] res = new int[n+1];
for(int i = 0; i < n+1; i++){
res[i] = ones(i);
}
return res;
}
public int ones(int n){
int res = 0;
while(n > 0){
n &= (n-1);
res++;
}
return res;
}
}
- To divide into equal and subsets
To give you one Contains only positive integers Of Non empty Array nums . Please decide whether you can divide this array into two subsets , Make the sum of the elements of the two subsets equal .
Example 1:
Input :nums = [1,5,11,5]
Output :true
explain : Arrays can be divided into [1, 5, 5] and [11] .
01 A variant of the backpack ,dp[i][j] ,i Express nums,j From 0 To target
State transition equation :
if(nums[i] > j){
dp[i][j] = dp[i-1][j];
continue;
}
if(nums[i] == j){
dp[i][j] = true;
continue;
}
if(nums[i] < j){
dp[i][j] = dp[i-1][j-nums[i]] || dp[i-1][j];
}
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for(int num: nums){
sum+=num;
}
if(sum%2 == 1){
return false;
}
int target = sum / 2;
boolean[][] dp = new boolean[nums.length][target+1];
for(int i=0; i < target+1; i++){
if(nums[0] == i){
dp[0][i] = true;
continue;
}
dp[0][i] = false;
}
for(int i = 1; i < nums.length; i++){
for(int j = 0; j < target+1; j++){
if(nums[i] > j){
dp[i][j] = dp[i-1][j];
continue;
}
if(nums[i] == j){
dp[i][j] = true;
continue;
}
if(nums[i] < j){
dp[i][j] = dp[i-1][j-nums[i]] || dp[i-1][j];
}
}
}
return dp[nums.length-1][target];
}
}
- Palindrome string
Give you a string s , Please count and return this string Palindrome string Number of .
Palindrome string Is reading the same string as reading it backwards .
Substring Is a sequence of consecutive characters in a string .
A substring with different start or end positions , Even if it's made up of the same characters , It's also seen as a different substring .
dp[i][j] Represents a string from i To j Is it palindrome
If j-i0( Single character ), It must be
If j-i1( Two characters ), If s[i]==s[j], It's also
If j-i>=2( Three or more ), Zhao Dapeng dp[i+1][j-1], If it is true, also s[i] == s[j], So it is
It should be noted that , When traversing , You can't 【0,1】【0,2】【0,3】 This way , need 【03】【1,3】,【2,3】【3,3】 This way
class Solution {
public int countSubstrings(String s) {
int length = s.length();
int res = 0;
boolean[][] dp = new boolean[length][length];
for(int j = 0; j < length;j++){
for(int i = 0; i<=j; i++){
if(j-i == 0){
dp[i][j] = true;
res++;
continue;
}
if(j-i == 1){
if(s.charAt(i) == s.charAt(j)){
dp[i][j] = true;
res++;
continue;
}
}
if(j-i > 1){
if(s.charAt(i) == s.charAt(j) && dp[i+1][j-1]){
dp[i][j] = true;
res++;
continue;
}
}
}
}
return res;
}
}
边栏推荐
- MySQL interview questions
- 網絡系統實驗:ping不通的問題解决
- Redis | very important Middleware
- Easy gene | target gene DNA methylation sequencing (target BS)
- Scroll view realizes drop-down refresh (to avoid the drop-down problem triggered by the initial refresh triggered value of true when onload enters the page)
- AVX instruction set accelerated matrix multiplication
- Tutorial on principles and applications of database system (047) -- MySQL query (IX): connection query
- 【数据挖掘工程师-笔试】2022年海尔 公司
- C language macro definition
- Implementation of singleton mode and prevention of reflection and serialization
猜你喜欢

QT入门篇(2.1初入QT的开始第一个程序)

1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮

XXL job realizes the code parsing of email sending warnings (line by line code interpretation)

What is the function of the select... For UPDATE statement? Can you lock tables or rows?

Development of main applet for business card traffic near the map

Image processing: Generation 3 × Window of 3

The most basic code interpretation of C language

Classic examples of C language - use 4 × The matrix displays all integers from 1 to 16 and calculates the sum of each row, column, and diagonal

项目场景:nvidia-smi Unable to datemine the device handle for GPU 0000:01:00.0: Unknow Error

Okaleido tiger NFT is about to log in to the binance NFT platform. Are you looking forward to it?
随机推荐
Dynamic rip configuration
Development of main applet for business card traffic near the map
Sword *offer -- reverse order of linked list
Off screen rendering & FBO
Sparksql design and introduction, 220722,
QT入门篇(2.1初入QT的开始第一个程序)
多源文件方式去访问全局变量的方式(extern用法)
postman测试接口在URL配置正确的情况下出现404或者500错误
项目场景:nvidia-smi Unable to datemine the device handle for GPU 0000:01:00.0: Unknow Error
Bean Validation自定义容器验证篇----06
PostgreSQL snapshot optimization globalvis new system analysis (greatly enhanced performance)
The high-quality digital collection of guochuang's "children's song line" is on sale, and you are invited to create a young martial arts Jianghu dream
Résumé du websocket minier
網絡系統實驗:ping不通的問題解决
Redis | very important Middleware
Solve the problem that MySQL inserts Chinese garbled code into the table
Memory forensics nssctf otterctf 2018 (replay)
这是一道大水题
Redis common commands
网络系统实验:ping不通的问题解决