码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Longest Increasing Subsequence

时间:2016-03-29 14:22:46      阅读:117      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!