Common problem-solving ideas of dynamic programming and Java implementation

Project Introduction

  • This project decomposes the common written interview questions of major factories, traces the source to the underlying implementation principles of data structures and algorithms, and knows what they are.
  • Establish a knowledge structure system for easy search, welcome more like-minded friends to join the project AlgorithmPractice, (issues and pull requests are welcome).

Part One: small test

This part of the content selected a few relatively simple dynamic programming topics to gradually understand what dynamic programming is.

Part Two: Introduce

This part of the content only gives the basic solution, if there is a more optimized solution, please leave a message below.

Part Three: Comprehensive highlights

The solution of this part of the content is not limited to dynamic programming, including greedy, backtracking, etc.

Start of text

1. The frog jumps the stairs

  • Title description: When climbing stairs, you can go up 1 step or 2 steps each time, and ask how many ways there are n steps of stairs
  • Code implementation: ClimbStairs , test case: ClimbStairsTest
  • Design ideas:
    • State transition equation:
statusNum[i] = statusNum[i-1] + statusNum[i-2];
  • Precautions:
    • For frequently accessed data, cache can be set for easy reading.

2. The largest sub-segment sum

  • Title description: Given an array, find the sum of the largest segment in the consecutive sub-arrays of this array
  • Code implementation: LSS , test case: LSSTest
  • Design ideas:
  • Dynamic programming method:
状态转换方程:
LargestSum[i] = Math.max(LargestSum[i-1] + Sequence[i], Sequence[i]);
  • Dynamic programming optimization method:
for(int i = 1; i < Sequence.length; i++){
    
    
	sum_temp += Sequence[i];
	if(sum_temp <= Sequence[i]){
    
      //新开始
		sum_temp = Sequence[i];   //sum清空
		begin_temp = i;           //假定的起始位置
	}
	if(sum < sum_temp){
    
    
		sum = sum_temp;           //记录最大值
		begin = begin_temp;       //假定的起始地址赋值给起始地址
		end = i;                  //结束地址包括 i
	}
}
  • Divide and conquer:
int leftValue = divide(Sequence, left, mid);
int rightValue = divide(Sequence, mid + 1, right);
int midValue = mid(Sequence, left, right);
  • Precautions:

3. The longest common subsequence

  • Title description: Find the largest matching substring of two strings
  • Code implementation: LCS , test case: LCSTest
  • Design ideas:
    • State transition equation:
num_matrix[row][column] = num_matrix[row-1][column-1]+1;
num_matrix[row][column] = num_matrix[row-1][column];
num_matrix[row][column] = num_matrix[row][column-1];
  • Precautions:

4. Palindrome application (Palindrome)

4.1. Determine whether a string belongs to a palindrome

  • Title description: Judge whether a given string is a palindrome, by default a single character is not enough to make a palindrome
  • Code:
public boolean PalindromeJudge(String testString) {
    
    
	if(testString == null || testString.length() == 0){
    
    
		return false;
	}
	boolean flag = new StringBuffer(testString).reverse().toString().equals(testString);
	return flag;
}
  • Design idea: string reverse and match
  • Precautions:
4.2. Add a character to construct a palindrome

  • Title description: Given a string s, you can add a character from it to make the remaining string a palindrome. If you get a palindrome by adding a character, return the position of the added element (starting address: 1) , Otherwise return -1, if it is a palindrome, return the middle position
  • Code implementation: CreatePalindromebyAdd , test case: CreatePalindromebyAddTest
  • Design ideas:
  • Precautions:
4.3, delete some characters to construct a palindrome

  • Title description: Given a string s, you can delete some characters from it, making the remaining string a palindrome. How to delete to make the palindrome the longest? Output the number of characters to be deleted
  • Code implementation: CreatePalindromebyDelete , test case: CreatePalindromebyDeleteTest
  • Design idea: the string is reversed, and the maximum similarity number is calculated by the LCS algorithm, then the numbers that are not similar need to be deleted.
  • Precautions:
4.4. Find the longest continuous palindrome substring in a given string

  • Title description:
  • Code implementation: FindPalindrome , test case: FindPalindromeTest
    • 4.4.1, violence law
    • 4.4.2, central diffusion method
    • 4.4.3, Manacher algorithm
  • Design ideas:
    • 4.4.1, violence law
    • 4.4.2, central diffusion method
    • 4.4.3, Manacher algorithm
  • Precautions:

5. The shortest delivery path

  • Description of the topic: A
    logistics delivery person p needs to deliver packages to 4 express points a, b, c, and d. What route does the delivery person need to choose to complete the shortest delivery. Assuming the starting point coordinates (0,0) of the dispatcher as shown in the figure, the dispatching route can only travel along the side of the square in the picture, each small square is square, and the side length is 1, such as the distance from p to d is 4. . Randomly input the coordinates of n delivery points, and find the shortest delivery route value (the distance from the starting point to complete the delivery of n points and back to the starting point).
    Insert picture description here
  • Code:
  • Design ideas:
    • how are you
    • Backtracking
  • Precautions:

6. The optimal scheduling problem

  • Title description: There are n tasks to be completed by k machines that can work in parallel, and the time required to complete task i is tasksspendTime. Try to design an algorithm to find the best schedule for completing these n tasks, so that the time to complete all tasks is the earliest
  • Code implementation: OptimalSchedule , test case: OptimalScheduleTest
  • Design ideas:
  • Precautions:

7. The longest increasing subsequence

  • Title description: In a given numerical sequence, find a sub-sequence so that the values ​​of the elements of this sub-sequence increase sequentially, and the length of this sub-sequence is as large as possible. The elements in the longest increasing subsequence are not necessarily consecutive in the original sequence
  • Code implementation: LIS , test case: LISTest
  • Design ideas:
  • Precautions:

8. The largest square

9. Edit distance

  • Title description:
    Edit distance refers to the minimum number of single-character editing operations required to convert one word to another between two words. There are only three single-character editing operations defined here: Insert, Delete and Substitution.
    For example, the two words "kitten" and "sitting" are converted from "kitten" to "sitting" "The minimum single-character editing operations required are:
    1. kitten → sitten (substitution of “s” for “k”)
    2. sitten → sittin (substitution of “i” for “e”)
    3. sittin → sitting (insertion of "G" at the end)
    Therefore, the edit distance between the words "kitten" and "sitting" is 3.
  • Code implementation: EditDistance , test case: EditDistanceTest
  • Design ideas:
    • State transition equation:
if (c1[i-1] == c2[j-1]) {
    
    
  comp[i][j] = comp[i - 1][j - 1];
} else {
    
    
  comp[i][j] = Math.min(Math.min(comp[i - 1][j - 1], comp[i][j - 1]), comp[i - 1][j]) + 1;
}
  • Precautions:

a, backpack problem (backpack)

  • Title description:
  • Code implementation: backpack , test case:
  • Design ideas:
  • Precautions:

b. Choir

  • Title description: There are n students standing in a row, and each student has an ability value. Niu Niu wants to select ChoseNum students in order from these n students, and the difference between the position numbers of two adjacent students is not more than d, so that The product of the ability values ​​of ChoseNum students is the largest. Can you return the largest product?
  • Code:
  • Design ideas:
    • Dynamic programming:
    • Backtracking method:
  • Precautions:

Guess you like

Origin blog.csdn.net/ljfirst/article/details/103082359