1. 程式人生 > >LeetCode|300. Longest Increasing Subsequence

LeetCode|300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

  • 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.

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

題目要求找出最長的遞增序列,可以不連續,但一定要遞增。

在LeetCode中的tag是dp

第一種解法不是dp

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] ans=new int[nums.length];
        if(nums.length<1)
            return 0;
        int max=1;
        ans[0]=1;
        for(int k=1;k<nums.length;k++){
            ans[k]=0;
        }
        for(int i=1;i<nums.length;i++){
            for(int j=0;j<i;j++){
                if(nums[i]>nums[j])
                    //找到比他小的最大長度
                    ans[i]=Math.max(ans[i],ans[j]);
            }
            ans[i]=ans[i]+1;
            max=Math.max(max,ans[i]);
            //System.out.println(max);
        }
        return max;
    }
}

找這個數之前比他小的序列的長度。