lintcode-medium-Longest Increasing Subsequence

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_common_subsequence_problem

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

 

动态规划:

用一个int数组表示把第i个数作为最后一个subsequence长度

所以只要后面的数比前面的数大,就更新最长子序列长度

最后遍历一边dp数组,选出最大值

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[] dp = new int[nums.length];
        int longest = 1;
        for(int i = 0; i < nums.length; i++)
            dp[i] = 1;
        
        for(int i = 0; i < dp.length; i++){
            for(int j = i + 1; j < dp.length; j++){
                if(nums[j] >= nums[i]){
                    dp[j] = Math.max(dp[j], dp[i] + 1);
                }
            }
        }
        
        for(int i = 0; i < dp.length; i++)
            longest = Math.max(longest, dp[i]);
        
        return longest;
    }
}

 

posted @ 2016-03-29 12:33  哥布林工程师  阅读(185)  评论(0编辑  收藏  举报