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

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

1 题目概述

1.1 题目出处

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

1.2 题目描述

2 动态规划

2.1 思路

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

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

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为最长子序列长度

参考文档

相关推荐
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 天前
322:零钱兑换(三种方法)
算法
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法