Longest Increasing Subsequence

Description

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

You code should return the length of the LIS.

 

 

找出最长的递增子序列,遍历数组,如果是以当前元素为起点的话,那么比如说, {1,4,2, 3, 5}这个数组,处理起来就比较麻烦。不妨换个思路:以当前元素作为序列的结尾,看它前面有多少个元素比它要小的。我们可以引入一个辅助数组counts[length], 其中counts[i]表示,在下标为i的元素前,有counts[i]个元素比它要小。counts数组内,每个元素的初始值都为1:

1  4  2  3  5

首先1为末尾,前面没有数比它要小,所以counts[0] == 1;然后到4为末尾,前面有个1比它小,那么counts[1] = counts[1] > counts[0]+1:counts[1]:counts[0]+1;

...

到5为末尾,首先1比它要小:counts[4] = counts[4]>counts[0]+1:counts[4]:counts[0]+1;然后关键是4和2: 4比它小:counts[4] = counts[4]>counts[1]+1?counts[4]:counts[1]+1; 此时counts[4]的值是2, 2比5要小:counts[4] = counts[4]>counts[2]+1?counts[4]:counts[2]+1;

可以注意到,此时counts[4]的值是没有更新的,此时,我们可以假设(注意,只是假设)前面的子序列为1,2,然后再继续进行前面的操作。最终,我们可以得到正确的结果,但是子序列并不一定是对的,因为这个方法,照过程来看,其实子序列是1,4,3,5。

public class Solution {
    /**
     * @param nums: An integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        // write your code here
        int length  = nums.length;
        if(length == 0){
            return 0;
        }
        int[] dp = new int[length];
        int res = 0;
        for(int end = 0; end < length; end++){
            dp[end] = 1;
            for(int start = 0; start < end; start++){
                if(nums[start] < nums[end]){
                    dp[end] = dp[end] > dp[start]+1 ? dp[end] : dp[start]+1;
                }
            }
            res = res > dp[end] ? res : dp[end];
        }
        return res;
    }
}

 

你可能感兴趣的:(Longest Increasing Subsequence)