算法-动态规划-最长递增子序列

算法-动态规划-最长递增子序列

1 题目概述

1.1 题目出处

https://leetcode.cn/problems/longest-increasing-subsequence/

1.2 题目描述

2 动态规划

2.1 思路

思考如果以dpi表示i位置的字符的最长递增子序列长度,那么很难找到dpi和dpi-1的关系,因为dpi没有携带是否取当前位置字符的信息。

那么我们以dpi表示以位置i结尾的字符的最长递增子序列长度,那么就可以找到dpi和dpi-1、dpi-2 ...的关系,只要numsj < numsi,则j 和 i就能组成递增子序列 ,我们从i-1比较到0,取dpj最大值+1作为dpi的值即可。

2.2 代码

java 复制代码
class Solution {
    int result = 0;
    public int lengthOfLIS(int[] nums) {
        if (nums.length == 0) {
            return result;
        }
        // 表示以指定位置结尾的最长递增子序列
        int[] dp = new int[nums.length];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[j] + 1, dp[i]);
                }
            }
            result = Math.max(result, dp[i]);
        }
        return result;
    }

}

2.3 时间复杂度

O(N^2)

2.4 空间复杂度

O(N)

3 二分查找

3.1 思路

3.2 代码

java 复制代码
class Solution {
    public int lengthOfLIS(int[] nums) {
        List<Integer> resultList = new ArrayList<>();
        resultList.add(nums[0]);
        for (int i = 1; i < nums.length; i++) {
            int lastIndex = resultList.size() - 1;
            if (nums[i] < resultList.get(lastIndex)) {
                // 比当前子序列尾元素还小,需要替换放入合适位置
                // 规则是替换掉resultList中最小的比当前元素nums[i]大的元素
                int m = 0, n = lastIndex;
                while (m < n) {
                    int mid = (m + n) / 2;
                    if (resultList.get(mid) < nums[i]) {
                        m = mid + 1;
                    } else if (resultList.get(mid) > nums[i]) {
                        n = mid - 1;
                    } else {
                        m = mid;
                        break;
                    }
                }
                if (nums[i] <= resultList.get(m)) {
                    resultList.set(m, nums[i]);
                } else {
                    resultList.set(m + 1, nums[i]);
                } 
                
            } else if (nums[i] > resultList.get(lastIndex)) {
                // 直接加入上升序列
                resultList.add(nums[i]);
            }
        }
        return resultList.size();
    }
}

3.3 时间复杂度

O(NlogN)

3.4 空间复杂度

O(K) K为最长子序列长度

参考文档

相关推荐
vibecoding日记1 天前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21381 天前
Verilog参数化游程编码RLE模块
算法
望易1 天前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络2 天前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron2 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩2 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹2 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术3 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望3 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法