最长递增子序列 -- 动规

300. 最长递增子序列

注意「⼦序列」和「⼦串」的区别,⼦串⼀定是连续的,⽽⼦序列不⼀定是连续的。

python 复制代码
class LengthOfLIS:
    """
    300. 最长递增子序列
    https://leetcode.cn/problems/longest-increasing-subsequence/description/
    """

    def solution(self, nums: List[int]):
        """
        方案一: 动态规划
        辅助数组 dp,dp[i] 表示以nums[i]结尾的子序列的最大长度
        时间复杂度O(N^2)
        空间复杂度O(N)
        :param nums:
        :return:
        """
        n = len(nums)
        dp = [1] * n
        for i in range(1, n):
            tmp = 0
            for j in range(0, i):
                if nums[j] < nums[i]:
                    tmp = max(tmp, dp[j])
            dp[i] = tmp + 1
        return max(dp)

    def solution2(self, nums: List[int]):
        """
        方案二:动态规划
        辅助数组 ends,ends[i] 代表目前所有长度为i+1的递增子序列的最小结尾。
        可推断出 ends 也是递增序列
        时间复杂度O(N*logN)
        空间复杂度O(N)
        :param nums:
        :return:
        """
        if not nums:
            return 0

        n = len(nums)
        ends = [0] * n
        ends[0] = nums[0]
        l, r, m, right = 0, 0, 0, 0
        res = 1
        for i in range(1, n):
            l = 0
            r = right
            while l <= r:
                m = (l + r) // 2
                if nums[i] > ends[m]:
                    l = m + 1
                else:
                    r = m - 1
            print(right, l)
            right = max(right, l)
            ends[l] = nums[i]
            res = max(res, l + 1)

        return res

    def solution3(self, nums: List[int]) -> int:
        """
        模拟蜘蛛纸牌
        :param nums:
        :return:
        """
        top = [0] * len(nums)
        #  牌堆数初始化为 0
        piles = 0
        for i in range(len(nums)):
            poker = nums[i]

            left, right = 0, piles
            while left < right:
                mid = left + (right - left) // 2
                if top[mid] > poker:
                    right = mid
                elif top[mid] < poker:
                    left = mid + 1
                else:
                    right = mid

            # 没找到合适的牌堆,新建⼀堆
            if left == piles:
                piles += 1
            # 把这张牌放到牌堆顶
            top[left] = poker

        return piles
相关推荐
旖-旎2 天前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
雪碧聊技术2 天前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
香辣牛肉饭3 天前
【算法】动态规划 最长公共子序列(LCS)
经验分享·笔记·算法·动态规划
旖-旎3 天前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
山顶夕景4 天前
【DWT】计算两不等序列相似度:DWT
算法·动态规划·检索·模式识别·相似度
雪碧聊技术5 天前
动态规划算法—01背包问题
算法·动态规划
旖-旎6 天前
LeetCode 494:目标和(动态规划/01背包问题)—— 题解
c++·算法·leetcode·动态规划·01背包
zephyr057 天前
动态规划-最长上升子序列问题
算法·动态规划
旖-旎7 天前
《LeetCode 416 分割等和子集》
c++·算法·leetcode·动态规划·背包问题
闪电悠米7 天前
力扣hot100-53.最大子数组和-动态规划详解
算法·leetcode·动态规划·dp·hot100