Longest Increasing Subsequence Show Result My Submissions

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


public class Solution {
    /**
     * @param nums: The integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = 0;
        int[] dp = new int[nums.length];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] < nums[j]) {
                    continue;
                }
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}

CORRECT DP:

f[i] denotes the LIS ending with nums[i]. 只有f(i)表示的LIS是以i结束的我们才能枚举所有的j < i,当num[j] <= num[i]的时候,f(i)的值是这些f(j)中的最大值+1. 这两种方式的区别在于,当使用第一种方式是,如果num[j] <= num[i],那么i一定可以从j推出,如果使用第二种方式,就算num[j]<=num[i], 我们仍需要比较num[j]中取的最后一个数是不是小于num[i].

参考:

7 8 9 10 11 12 4 2 4 5 3 7. 第一种方式,f(2) = 1,到3的时候我们看到前面2比3小,所以f(3) = f(2) + 1 = 2.

如果用第二种方式,那么 f(2) = 6, f (3) = 7 就错了。。我们要比较的是当前的num[i]与前面那么多j个lis中最后取的元素的大小关系。

INCORRECT DP:

f[i] denotes the LIS up to i.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值