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

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

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

参考文档

相关推荐
东方芷兰39 分钟前
算法笔记 04 —— 算法初步(下)
c++·笔记·算法
JNU freshman41 分钟前
图论 之 迪斯科特拉算法求解最短路径
算法·图论
青松@FasterAI1 小时前
【NLP算法面经】本科双非,头条+腾讯 NLP 详细面经(★附面题整理★)
人工智能·算法·自然语言处理
旅僧1 小时前
代码随想录-- 第一天图论 --- 岛屿的数量
算法·深度优先·图论
Emplace1 小时前
ABC381E题解
c++·算法
若兰幽竹2 小时前
【机器学习】衡量线性回归算法最好的指标:R Squared
算法·机器学习·线性回归
居然有人6543 小时前
23贪心算法
数据结构·算法·贪心算法
SylviaW083 小时前
python-leetcode 37.翻转二叉树
算法·leetcode·职场和发展
h^hh4 小时前
洛谷 P3405 [USACO16DEC] Cities and States S(详解)c++
开发语言·数据结构·c++·算法·哈希算法
玦尘、4 小时前
位运算实用技巧与LeetCode实战
算法·leetcode·位操作