Longest Increasing Subsequence

Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.code

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.字符串

Your algorithm should run in O(n2) complexity.it

Follow up: Could you improve it to O(n log n) time complexity?io

  1. 解題思路class

求沒必要連續的最長升序字符串長度,採用動態規劃,利用狀態dp[i]表示以字符nums[i]結尾的最長子串的長度,那麼狀態轉移方程就是:
dp[i]=Math.max(dp[i],dp[j]+1);0<=j<i;
且nums[j]必須小於nums[i]
另外還需維護一個最大長度。im

2.代碼sort

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums.length==0) return 0;
        int[] dp=new int[nums.length];
        int maxLength=0;
        for(int i=0;i<nums.length;i++){
            dp[i]=1;
            for(int j=0;j<i;j++){
                if(nums[j]<nums[i]){
                    dp[i]=Math.max(dp[i],dp[j]+1);
                }
            }
            maxLength=Math.max(maxLength,dp[i]);
        }
        return maxLength;
       
    }
  
}
相關文章
相關標籤/搜索