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;
       
    }
  
}
相关文章
相关标签/搜索