首页 > 其他 > 详细

lintcode-medium-Longest Increasing Subsequence

时间:2016-03-29 14:22:18      阅读:192      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

lintcode-medium-Longest Increasing Subsequence

原文:http://www.cnblogs.com/goblinengineer/p/5332479.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!