动态规划动态规划

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

2018-06-10  本文已影响0人  Arthur_7724

一、题目

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_最长公共子序列

上一篇 下一篇

猜你喜欢

热点阅读