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?


dp解:递推式:dp[i] = max(dp[j]) for (j < i && nums[j] < nums[i]) + 1,最后注意返回的是dp数组里最大的而不是最后一个。以及一些int variable设成0或者1或者-1也有讲究,具体看代码注释。

时间复杂度O(MN),M N分别为两个string的长度。

Runtime: 9 ms, faster than 73.39% of Java online submissions for Longest Increasing Subsequence.

Memory Usage: 37.1 MB, less than 96.47% of Java online submissions for Longest Increasing Subsequence.

class Solution {
    public int lengthOfLIS(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int result = 1;  // if assigning as 0, it will return 0 for 1 element array
        for (int i = 1; i < nums.length; i++) {
            int max = 0;  // assigning as 0 can simplify the dp[i] = max + 1
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    max = Math.max(max, dp[j]);
                }
            }
            dp[i] = max + 1;
            result = Math.max(result, dp[i]);
        }
        // attention! not returning the last element, it's returning the largest
        return result;
    }
}

另外也可以dp+binary search,以及递归。留坑。

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页