300. Longest Increasing Subsequence

本文探讨了如何求解最长递增子序列(LIS)问题,通过动态规划的方法实现了一个O(n^2)复杂度的解决方案,并提供了详细的代码示例。文章还讨论了如何优化算法至O(n log n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,

Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?


第二遍 还是没做出来 。。。  
倒是很快看明白了 知道应该用dp 就想一下 dp存什么 后面的能继续使用
难点还在于 递推表达式不好想 应该是 

dp[i]=max(dp[j])+1,0j<i

LISlength=max(dp[i]),0i<n

10 9 2 5 3 4 7

怎样是2,3,4 而不是2,5 也就是怎样让3能接上2?
遍历3之前所有可以接上的

public int lengthOfLIS(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int maxans = 1;
        for (int i = 1; i < dp.length; i++) {
            int maxval = 0;
            for (int j = 0; j < i; j++) {                         
                if (nums[i] > nums[j]) {//找出所有将nums[i]加入仍然是递增序列的序列
                    maxval = Math.max(maxval, dp[j]);//选择长度最大的那个 拼接上nums[i] 这样 就还是最长的子序列
                }
            }
            dp[i] = maxval + 1;
            maxans = Math.max(maxans, dp[i]);
        }
        return maxans;
    }

//也就是说 从dp[i]是指可以将nums[i]加入之后仍然是递增子序列中 长度最大的那个 dp[0]到dp[n]分别代表把dp[i]包含进来 最长的递增子序列 然后取最长的长度就可以了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值