【leetcode每日刷题】【DP】300. Longest Increasing Subsequence

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_38103546/article/details/100774723

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?

使用一个记忆数组保存当前元素作为最大元素的最大递增数列,对于每个元素,首先初始化该元素的记忆数组的值为1,然后遍历前面的所有元素,获得当前元素和前面比当前元素小的元素+1之间的最大值。

if(nums[j] < nums[i]){
                    memory[i] = Math.max(memory[j]+1, memory[i]);
                    max = Math.max(memory[i], max);
                }
10 9 2 5 3 7 101 18
1 1 1 2 2 3 4 4
class num300 {
    public int lengthOfLIS(int[] nums) {
        if(nums.length == 0) return 0;
        int max = 1;
        int[] memory = new int[nums.length];
        for(int i=0; i<nums.length; i++){
            memory[i] = 1;
        }
        for(int i=1; i<nums.length; i++){
            for(int j=0; j<i; j++){
                if(nums[j] < nums[i]){
                    memory[i] = Math.max(memory[j]+1, memory[i]);
                    max = Math.max(memory[i], max);
                }
            }
        }
        return max;
    }
    public static void main(String[] args) {
        num300 s = new num300();
        int[] nums = new int[]{10,9,2,5,3,7,101,18};
        System.out.println(s.lengthOfLIS(nums));
    }
}

猜你喜欢

转载自blog.csdn.net/m0_38103546/article/details/100774723
今日推荐