Thursday, April 20, 2017

[LintCode] 76 Longest Increasing Subsequence 解题报告

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

You code should return the length of the LIS.



Clarification
What's the definition of longest increasing subsequence?

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

https://en.wikipedia.org/wiki/Longest_increasing_subsequence



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 [2, 4, 5, 7], return 4



Challenge
Time complexity O(n^2) or O(nlogn)



思路
DP。
f[i]表示到i以及i之前,包含i的可以达到的最大LIS。
在check到i的时候,我们看i之前所有的位置,如果可以加上i组成更大的ILS,那么我们可以更新i这个位置的ILS。


Code
public class Solution {
    /**
     * @param nums: The integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        // write your code here
        
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int[] f = new int[nums.length];
        int max = 1;
        
        for (int i = 0; i < nums.length; i++) {
            f[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    f[i] = Math.max(f[i], f[j] + 1);
                }
            }
            max = Math.max(max, f[i]);
        }
        
        return max;
    }
}