当前位置:网站首页>Longest strictly increasing subsequence

Longest strictly increasing subsequence

2022-06-11 19:07:00 AlbertOS

introduce

Given an array arr, return arr The length of the longest strictly increasing subsequence of

Subarray is continuous , such as [1,3,5,7,9] The subarrays of are [1,3],[3,5,7] wait , however [1,3,7] It's not a subarray .

  Example :
    Input : [10,9,2,5,3,7,101,18]
    Output : 4
   explain :  The longest ascending subsequence is  [2,3,7,101], Its length is  4.

How to solve the problem

Using the idea of dynamic programming , use i Traversal array , And then use j Ergodic less than i The data of , If i The data of is greater than j And dp[i] The length of is less than dp[j]+1 The length of , Then write it down ;
In fact, I know how to solve problems and the recurrence formula , It's easy to write ,
D ( x ) = { m a x ( d p [ j ] + 1 , d p [ i ] ) , 0 < = j < i And a r r [ j ] < a r r [ i ] 1 , 0 < = j < i And a r r [ j ] > a r r [ i ] D(x) = \begin{cases} max(dp[j]+1,dp[i] ), & 0<=j<i And arr[j]<arr[i] \\ 1,& 0<=j<i And arr[j]>arr[i] \\ \end{cases} D(x)={ max(dp[j]+1,dp[i]),1,0<=j<i And arr[j]<arr[i]0<=j<i And arr[j]>arr[i]

java Code

class Solution {
    
    public int lengthOfLIS(int[] nums) {
    
        if (nums.length == 0) {
    
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int maxans = 1;
        for (int i = 1; i < nums.length; i++) {
    
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
    
                if (nums[i] > nums[j]) {
    
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            maxans = Math.max(maxans, dp[i]);
        }
        return maxans;
    }
}

Complexity analysis

  • Time complexity : O ( n 2 ) O(n^2) O(n2), among n Is an array nums The length of . The number of states of dynamic programming is n, Calculation state dp[i] when , need O(n) Time traversal d p [ 0 … i − 1 ] d p [ 0 … i − 1 ] dp[0 \ldots i-1]dp[0…i−1] dp[0i1]dp[0i1] All states , So the total time complexity is O ( n 2 ) O(n^2) O(n2)

  • Spatial complexity : O ( n ) O(n) O(n), Additional length required is n Of dp Array .

原网站

版权声明
本文为[AlbertOS]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111800379126.html