美文网首页动态规划动态规划
3. DP_Lintcode76 最长增长(上升)子序列Long

3. DP_Lintcode76 最长增长(上升)子序列Long

作者: Arthur_7724 | 来源:发表于2018-06-10 17:55 被阅读0次

一、题目

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

You code should return the length of the LIS.

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

二、解题思路

方案一:动态规划 时间复杂度O(n*n)

dp[i] 表示以i结尾的子序列中LIS的长度。然后我用 dpj 来表示在i之前的LIS的长度。然后我们可以看到,只有当 a[i]>a[j] 的时候,我们需要进行判断,是否将a[i]加入到dp[j]当中。为了保证我们每次加入都是得到一个最优的LIS,有两点需要注意:第一,每一次,a[i]都应当加入最大的那个dp[j],保证局部性质最优,也就是我们需要找到 max(dpj) ;第二,每一次加入之后,我们都应当更新dp[j]的值,显然, dp[i]=dp[j]+1 。 如果写成递推公式,我们可以得到 dp[i]=max(dpj)+(a[i]>a[j]?1:0) 。

三、解题代码

public int longestIncreasingSubsequence(int[] nums) {  
    int[] f = new int[nums.length];  
    int max = 0;  
    for (int i = 0; i < nums.length; i++) {  
        f[i] = 1;  
        for (int j = 0; j < i; j++) {  
            if (nums[j] < nums[i]) {  
                f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1;  
            }  
        }  
        if (f[i] > max) {  
            max = f[i];  
        }  
    }  
    return max;  
}  

下一篇: 4. DP_LeetCode121/122/123 &终极[k]次交易
上一篇: 2. DP_最长公共子序列

相关文章

  • 3. DP_Lintcode76 最长增长(上升)子序列Long

    一、题目 Given a sequence of integers, find the longest incre...

  • 公共子序列问题

    最长公共子序列 最长上升子序列 最长公共上升子序列

  • LintCode 最长上升子序列

    给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。 说明 最长上升子序列的定义: 最长上升子序列问...

  • LintCode 最长上升子序列

    题目 给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。 说明最长上升子序列的定义:最长上升子序列...

  • 最长上升子序列

    最长上升子序列(Longest Increasing Subsequence) 最长上升子序列方案数

  • LintCode 最长上升子序列

    题目 给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。说明最长上升子序列的定义:最长上升子序列问...

  • 76. 最长上升子序列

    描述 给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。 说明 最长上升子序列的定义: 最长上升子...

  • 76. 最长上升子序列

    给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。说明最长上升子序列的定义:最长上升子序列问题是在...

  • lintcode 最长上升子序列

    给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。说明最长上升子序列的定义:最长上升子序列问题是在...

  • 子序列问题

    最长公共子序列 最长上升/下降/不升/不降子序列

网友评论

    本文标题:3. DP_Lintcode76 最长增长(上升)子序列Long

    本文链接:https://www.haomeiwen.com/subject/uhcqeftx.html