Test Development Preparation for Autumn Recruitment Interview 14-Dynamic Planning for Niu Ke Brushing Questions

After working hard for so many years, looking back, it is almost all long setbacks and sufferings. For most people's life, smooth sailing is only occasional, and frustration, unbearable, anxiety and confusion are the main theme. We take the stage we did not choose, play the script we did not choose. Keep going!

Table of contents

1. Fibonacci sequence

2. Jumping the stairs

3. Climbing stairs with minimum cost

4. The longest common subsequence (2)

5. The longest common substring

6. The number of different paths (1)

7. The minimum path sum of the matrix

8. Translate numbers into strings

9. Exchange change

10. The longest ascending subsequence (1)

11. Maximum sum of consecutive subarrays

12. The longest palindrome substring

13. Convert numeric strings to IP addresses

14. Edit distance (1)

15. The longest parenthesized substring

16. Robbery 1

17. Robbery 2

18. The best time to buy and sell stocks (1)

19. The best time to buy and sell stocks (2)

20. The best time to buy and sell stocks (3)


1. Fibonacci sequence

Topic Link: Fibonacci Sequence_Niuke Question Master_Niuke.com

Idea: f(n) = f(n-1) + f(n-2)

Java version:

public class Solution {
    public int Fibonacci(int n) {
        if(n==1 || n==2){
            return 1 ;
        }
        return Fibonacci(n-1) + Fibonacci(n-2) ;
    }
}

2. Jumping the stairs

Topic Link: Jumping Stairs_Niuke Question Master_Niuke.com

Idea: The same idea as the Fibonacci sequence, but the exit is different.

Java version:

public class Solution {
    public int jumpFloor(int target) {
        if(target==1 ){
            return 1 ;
        }
        if(target==2){
            return 2 ;
        }

        return jumpFloor(target-1) + jumpFloor(target-2) ;
    }
}
public class Solution {
    public int jumpFloor(int target) {
      int [] ans = new int [target] ;
      ans[0] = 1 ;
      if(ans.length > 1)
      ans[1] = 2 ;
      for(int i=2; i<ans.length; i++){
        ans[i] = ans[i-1] + ans[i-2]  ;
      }
      return ans[target-1] ;
    }
}

3. Climbing stairs with minimum cost

Topic link: Minimum cost to climb stairs_Niuke题目_Niuke.com
Idea: The minimum cost to climb to the current staircase=min(minimum cost + cost of going up the stairs, minimum cost of going up the stairs + cost)
Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param cost int整型一维数组 
     * @return int整型
     */
    public int minCostClimbingStairs (int[] cost) {
        // write code here
        int [] dp = new int [cost.length+1] ;
        dp[0] = dp[1] = 0 ;
        for(int i=2; i<dp.length; i++){
            dp[i] = Math.min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]) ;
        }
        return dp[cost.length] ;
    }
}

4. The longest common subsequence (2)

Topic Link: Longest Common Subsequence (2)_Niuke Topic_Niuke.com

Idea: first find the length of the longest common subsequence, then find the longest common subsequence from back to front, and finally flip it.

Java version:

import java.util.*;


public class Solution {
    /**
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String s1, String s2) {
        // write code here
        int n = s1.length() + 1, m = s2.length() + 1 ;
        int [][] dp = new int [n][m] ;
        for(int i=1; i<n; i++){
            for(int j=1; j<m; j++){
                if(s1.charAt(i-1) == s2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] + 1 ;
                }else{
                    dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]) ;
                }
            }
        }
        StringBuilder sb = new StringBuilder("") ; 
        int l1 = s1.length(), l2 = s2.length() ;
        while(l1 > 0 && l2 > 0){
            if(s1.charAt(l1-1) == s2.charAt(l2-1)){
                sb.append(s1.charAt(l1-1)) ;
                l1 -- ;
                l2 -- ;
            }else{
                if(dp[l1-1][l2] > dp[l1][l2-1]){
                    l1 -- ;
                }else{
                    l2 -- ;
                }
            }
        }
        if(sb.length() == 0){
            return "-1" ;
        }
        return sb.reverse().toString() ;
    }
}

5. The longest common substring

Topic Link: Longest Common Substring_Niuke Question Master_Niuke.com

Idea: Find the length of the longest common string, record the subscript, and then directly intercept the string.
Java version:
 

import java.util.*;


public class Solution {
    /**
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String str1, String str2) {
        // write code here
        int n = str1.length() + 1, m = str2.length() + 1 ;
        int [][] dp = new int [n][m] ;
        int max = 0, pos = 0 ;
        for(int i=1; i<n; i++){
            for(int j=1; j<m; j++){
                if(str1.charAt(i-1) == str2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] + 1 ;
                }else{
                    dp[i][j] = 0 ;
                }
                if(dp[i][j] > max){
                    max = dp[i][j] ;
                    pos = i - 1 ;
                }
            }
        }
        return str1.substring(pos-max+1, pos+1) ;
    }
}

6. The number of different paths (1)

Topic Link: Number of Different Paths (1)_Niuke Topic_Niuke.com

Idea: dp[i][j] = dp[i-1][j] + dp[i][j-1]
Java version:

import java.util.*;


public class Solution {
    /**
     * 
     * @param m int整型 
     * @param n int整型 
     * @return int整型
     */
    public int uniquePaths (int m, int n) {
        // write code here
        int [][] dp = new int [m+1][n+1] ;
        for(int i=1; i<=m; i++){
            for(int j=1; j<=n; j++){
                if(i==1 || j==1){
                    dp[i][j] = 1 ;
                }else{
                    dp[i][j] = dp[i-1][j] +dp[i][j-1] ;
                }
            }
        }
        return dp[m][n] ;
    }
}

7. The minimum path sum of the matrix

Topic Link: The Minimum Path Sum of a Matrix

思路:dp[i][j] = min(dp[i-1][j],dp[i][j-1])+matrix[i][j]

Java version:

import java.util.*;


public class Solution {
    /**
     * 
     * @param matrix int整型二维数组 the matrix
     * @return int整型
     */
    public int minPathSum (int[][] matrix) {
        // write code here
        int n = matrix.length, m = matrix[0].length ;
        int [][] dp = new int [n][m] ;
        dp[0][0] = matrix[0][0] ;
        for(int i=0; i<n; i++){
            for(int j = 0; j<m; j++){
                if(i==0 && j==0){
                    continue ;
                }
                if(i==0){
                    dp[i][j] = dp[i][j-1] + matrix[i][j] ;
                }else if(j == 0){
                    dp[i][j] = dp[i-1][j] + matrix[i][j] ;
                }else{
                    dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + matrix[i][j] ;
                }
            }
        }
        return dp[n-1][m-1] ;
    }
}

8. Translate numbers into strings

Topic Link: Translate Numbers into Strings

Idea: There are two encoding methods for 11-19, 21-26, and the rest are either one or zero.

Java version:

import java.util.*;


public class Solution {
    /**
     * 解码
     * @param nums string字符串 数字串
     * @return int整型
     */
    public int solve (String nums) {
        // write code here
        if(nums.equals("0")){
            return 0 ;
        }
        if(nums.equals("10") || nums.equals("20")){
            return 1 ;
        }
        for(int i=1; i<nums.length(); i++){
            if(nums.charAt(i) == '0'){
                if(nums.charAt(i-1) != '1' && nums.charAt(i-1) != '2'){
                    return 0 ;
                }
            }
        }
        int [] dp = new int [nums.length()+1];
        Arrays.fill(dp,1) ;
        for(int i=2; i<dp.length; i++){
            if((nums.charAt(i-2) == '1' && nums.charAt(i-1) != '0') || (nums.charAt(i-2)== '2' && nums.charAt(i-1) > '0' && nums.charAt(i-1) < '7')){
                dp[i] = dp[i-1]  + dp[i-2] ;
            }else{
                dp[i] = dp[i-1] ;
            }
        }
        return dp[nums.length()] ;
    }
}





9. Exchange change

Topic Link: Exchange Change (1)_Niuke Topic Master_Niuke.com

Idea: List all dp[i] of 1-aim, recursive formula: dp[i] = Math(dp[i], dp[j-arr[i]] + 1), time complexity O(n* aim)

Java version:

import java.util.*;


public class Solution {
    /**
     * 最少货币数
     * @param arr int整型一维数组 the array
     * @param aim int整型 the target
     * @return int整型
     */
    public int minMoney (int[] arr, int aim) {
        // write code here
        int [] dp = new int [aim+1] ;
       
         Arrays.fill(dp, aim+1) ;
         dp[0] = 0 ;
         //要列举所有的1-aim才行,并且每一个都要从所有的里面递推出最小的种类数目
        for(int j=1; j<=aim ; j++){
        for(int i=0; i<arr.length; i++){
            if(arr[i] <= j){
                dp[j] = Math.min(dp[j], dp[j - arr[i]] + 1) ;
            }
        }
        }
        int result = dp[aim] > aim ? -1 : dp[aim] ;
        return result ;
    }
}

10. The longest ascending subsequence (1)

Topic Link: Longest Ascending Subsequence (1)_Niuke Topic_Niuke.com

Idea: dp[i] represents the length of the longest ascending subsequence ending with i, double-layer loop, update dp[i] when arr[i] > arr[j] && dp[i] < dp[j]+1 .

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 给定数组的最长严格上升子序列的长度。
     * @param arr int整型一维数组 给定的数组
     * @return int整型
     */
    public int LIS (int[] arr) {
        // write code here
        int [] dp = new int [arr.length] ;
        if(arr.length == 0){
            return 0 ;
        }
        Arrays.fill(dp, 1) ;
        int max = 1 ;

        for(int i=1; i<arr.length; i++){
            for(int j=0; j<i; j++){
                if(arr[i] > arr[j] && dp[i] < dp[j]+1){
                    dp[i] = dp[j] + 1 ;
                }
                if(max < dp[i]){
                    max = dp[i] ;
                }
            }
        }
        return max ;
    }
}

11. Maximum sum of consecutive subarrays

Topic Link: The Maximum Sum of Consecutive Subarrays

Idea: Only when the number accumulated before is greater than 0, the accumulation is allowed to be the current one, otherwise, the accumulation will continue from the current one, and the maximum value during the accumulation process is the maximum sum of the continuous sub-arrays.

Java version:

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
       //最好保证时间复杂度为O(n),空间复杂度为O(1)
       int sum = 0 ;
       int max = -100 ;

       for(int i=0; i<array.length; i++){
        if(sum + array[i] > array[i]){
            sum += array[i] ;
        }else{
            sum = array[i] ;
        }
        if(max < sum){
            max = sum ;
        }
       }
       return max ;
       
    }
}

12. The longest palindrome substring

Topic Link: Longest Palindrome Substring_Niuke Topic_Niuke.com

Idea: dp[i][j] represents the longest palindrome string from i to j, but the length should be used as the outer loop.

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param A string字符串 
     * @return int整型
     */
    public int getLongestPalindrome (String A) {
        // write code here
        int max = 0 ;
        int n = A.length() ;
        boolean [][] dp = new boolean [n][n] ;
        //dp[i][i+j]:i表示开始,j表示长度,从i到i+j的最长回文字串啊
        for(int j = 0; j<n; j++){
            for(int i=0; i+j<n; i++){
              if(j==0){
                dp[i][i+j] = true ;
              }else if(j==1){
                dp[i][i+j] = (A.charAt(i) == A.charAt(i+j))  ;
              }else{
                dp[i][i+j] = (A.charAt(i) == A.charAt(i+j) && dp[i+1][i+j-1]) ;
              }
              if(dp[i][i+j] && j+1>max){
                max = j + 1 ;
              }
            }
        }
        return max ;
    }
}

13. Convert numeric strings to IP addresses

Topic Link: Converting Numerical Strings to IP Addresses

Idea: Circularly judge the strings that meet the length and ip address requirements and add them to the set.

Java version:

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return string字符串ArrayList
     */
    public ArrayList<String> restoreIpAddresses (String s) {
        // write code here
        ArrayList<String> list = new ArrayList<>() ;
        for(int i=1; i<=3; i++){
            for(int j=1; j<=3; j++){
                for(int k=1; k<=3; k++){
                    for(int l=1; l<=3; l++){
                        if(i+j+k+l==s.length()){
                            String s1 = s.substring(0,i) ;
                            String s2 = s.substring(i,i+j) ;
                            String s3 = s.substring(i+j, i+j+k) ;
                            String s4 = s.substring(i+j+k, i+j+k+l) ;
                            if(f(s1) && f(s2) && f(s3) && f(s4)){
                                String tmp = s1 + "." + s2 + "." + s3 + "." + s4 ;
                                list.add(tmp) ;
                            }
                        }
                    }
                }
            }
        }
        return list ;
    }
    public boolean f(String s){
        if(s.length() == 1){
            return true ;
        }else if(s.charAt(0) != '0' && Integer.parseInt(s) >= 10 && Integer.parseInt(s) <= 255){
            return true ;
        }
        return false ;
    }
}

14. Edit distance (1)

Topic Link: Edit Distance (1)_Niuke Topic_Niuke.com

Idea: dp[i][j] represents the minimum number of operations from the beginning to str1[i], str2[j].

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param str1 string字符串 
     * @param str2 string字符串 
     * @return int整型
     */
    public int editDistance (String str1, String str2) {
        // write code here
        //dp[i][j]表示从起点开始到str1[i]与str2[j]的最小操作次数
        int n1 = str1.length(), n2 = str2.length() ;
        int [][] dp = new int [n1+1][n2+1] ;
        for(int i=1; i<=n1; i++){
            dp[i][0] = dp[i-1][0] + 1 ;
        }
        for(int j=1; j<=n2; j++){
            dp[0][j] = dp[0][j-1] + 1 ;
        }
        for(int i=1; i<=n1; i++){
            for(int j=1; j<=n2; j++){
                if(str1.charAt(i-1) == str2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] ;
                }else{
                    dp[i][j] = Math.min(dp[i-1][j-1],Math.min(dp[i-1][j], dp[i][j-1])) + 1 ;
                }
            }
        }
        return dp[n1][n2] ;
    }
}

15. The longest parenthesized substring

Topic link: The longest parenthesis substring_Niuke Topic_Niuke.com

Idea: Realize with the help of the stack. If the left parenthesis is put on the stack, it needs to judge when it encounters the right parenthesis. If the stack element is less than 2, it will be popped out of the stack first, and the current element will be subscripted into the stack. Otherwise, it will be popped out of the stack directly, and the current Get the longest bracket string.

Java version:

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int longestValidParentheses (String s) {
        // write code here
        Stack <Integer> stack = new Stack<>() ;
        stack.add(-1) ;
        int ans = 0 ;
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i) == '('){
                stack.add(i) ;
            }else{
                if(stack.size() > 1){
                    stack.pop() ;
                    ans = Math.max(ans, i-stack.peek()) ;
                }else{
                    stack.pop() ;
                    stack.add(i) ;
                }
            }
        }
        return ans ;
    }
}

16. Robbery 1

Topic link: House robbery (1)_Niuke Topic_Niuke.com

Idea: Steal another family, in this case, recursively dp[i] = max(dp[i-1], dp[i-2]+nums[i]);

Java version:
 

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型
     */
    public int rob (int[] nums) {
        // write code here
        int n = nums.length ;
        int [] dp = new int [n] ;
        dp[0] = nums[0] ;
        if(n>1){
            dp[1] = Math.max(nums[0], nums[1]) ;
        }
        for(int i=2; i<n; i++){
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]) ;
        }
        return dp[n-1] ;
    }
}

17. Robbery 2

Topic link: House robbery (2)_Niuke Topic_Niuke.com

Idea: For a ring-shaped circle, it is necessary to judge whether the first one is taken, and it can be discussed in two possibilities.

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型
     */
    public int rob (int[] nums) {
        // write code here
        int n = nums.length ;
        int [] dp = new int [n] ;
        dp[0] = nums[0] ;
        dp[1] = nums[0] ;
        for(int i=2; i<n; i++){
            if(i==n-1){
                dp[i] = Math.max(dp[i-1], dp[i-2]) ;
            }else{
                dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]) ;
            }
        }
        int ans = dp[n-1] ;
        Arrays.fill(dp, 0) ;
        dp[1] = nums[1] ;
        for(int i=2; i<n; i++){
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]) ;
        }
        int max = (ans > dp[n-1]) ? ans : dp[n-1] ;
        return max ;
     }
}

18. The best time to buy and sell stocks (1)

Topic link: The best time to buy and sell stocks (1)_Niuke题目_Niuke.com

Idea: It is more reasonable and general to use the holding and throwing ideas of two-dimensional arrays.

Java version:

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int n = prices.length ;
        int [][] dp = new int [n][3] ;
        dp[0][0] = 0 ;
        dp[0][1] = -prices[0] ;
        dp[0][2] = 0 ;
        for(int i=1; i<n; i++){
            dp[i][0] = dp[i-1][0] ;
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]) ;
            dp[i][2] = Math.max(dp[i-1][2], dp[i-1][1] + prices[i]) ;
        }
        return dp[n-1][2] ;
    }
}

19. The best time to buy and sell stocks (2)

Topic link: The best time to buy and sell stocks (2)

Idea: It’s still the old template, but it can be traded multiple times, and the recursive expression is slightly modified. Note: start traversing from 1

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int n = prices.length ;
        int [][] dp = new int [n][2] ;
        dp[0][0] = 0 ;
        dp[0][1] = -prices[0] ;

        for(int i=1; i<n; i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]) ;
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]) ;
        }
        return dp[n-1][0] ;
    }
}

20. The best time to buy and sell stocks (3)

Topic link: The best time to buy and sell stocks (3)_Niuke Topic Ba_Niuke.com

Idea: buy tickets twice, dp[n][5] represent no holding, holding and throwing for the first time, holding and throwing for the second time respectively.

Java version:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 两次交易所能获得的最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int n = prices.length ;
        int [][] dp = new int [n][5] ;
        dp[0][0] = 0 ;
        dp[0][1] = -prices[0] ;
        dp[0][2] = dp[0][3] = dp[0][4] = -100000 ;
        for(int i=1; i<n; i++){
            dp[i][0] = dp[i-1][0] ;
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]) ;
            dp[i][2] = Math.max(dp[i-1][2], dp[i-1][1] +  prices[i]) ;
            dp[i][3] = Math.max(dp[i-1][3], dp[i-1][2] - prices[i]) ;
            dp[i][4] = Math.max(dp[i-1][4], dp[i-1][3] + prices[i]) ;
        } 
        return dp[n-1][4] ;
    }
}

Guess you like

Origin blog.csdn.net/nuist_NJUPT/article/details/130877312
Recommended