1

Longest Increasing Subsequence

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Example
For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4

分析

由于是求最长的子序列,可以index不连续,可以考虑用DP解决。比如dp[i]表示以为i元素结尾的子序列的最大长度,那么可以根据所有dp[j](j < i)来得到dp[i]的值。

这道题也可以有简单的Follow up, 比如找index是连续的增加或减少的子序列最大长度。
由于index是连续,直接两个指针就可以解决,注意两种可能性,一种增大,一种减小。

Example
For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.
For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.

这道题与另外一道题比较也比较类似,可参考Binary Tree Longest Consecutive Sequence

复杂度

time: O(n^2), space: O(n)

代码

public class Solution {
    public int longestIncreasingSubsequence(int[] nums) {
        if (nums.length == 0)
            return 0;
        int max = 0;
        int[] dp = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] >= nums[j]) // 必须是递增
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(max, dp[i]); // 更新全局最大值
        }
        return max;
    }
}

Follow up

time: O(n), space: O(n)

public class Solution {
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        int l = 0;
        int r = 1;
        int max = 1;
        while (r < A.length) {
            if (A[r] > A[r - 1]) {
                // 连续增加的情况
                while (r < A.length && A[r] > A[r - 1]) {
                    r++;
                }
            } else {
                // 连续减小的情况
                while (r < A.length && A[r] < A[r - 1]) {
                    r++;
                }
            }
            max = Math.max(max, r - l);
            l = r - 1;
        }
        return max;
    }
}

微斯渝
39 声望15 粉丝