Leetcode 300. Longest Increasing Subsequence

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 300. Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

2. Solution

**解析:**Version 1,最长递增子序列,典型的动态规划问题,定义状态:以nums[i]作为结尾元素的最长递增子序列的长度,状态转移方程:遍历nums[i]之前的元素nums[j],如果nums[i] > nums[j],则其最长递增子序列的长度为max(dp[i], dp[j] + 1),遍历之后,可以找到以nums[i]作为结尾元素的最长递增子序列长度,最终返回的是所有元素的最长递增子序列长度中最长的一个。Version 2是一种技巧,使用order作为有序序列保持最长递增子序列长度,当新元素比有序序列的最后一个元素大时,此时增加新元素到有序序列中,否则,则将新元素插入到当前序列中,替换比其大或相等的元素,保证左侧元素都比它小,此时长度不变,order中始终保留较小的元素,这样利于插入新元素。order的长度等于最长递增子序列长度,但order的数据不一定等于最长递增子序列的数据。

  • Version 1
class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        dp = [1] * n
        for i in range(1, n):
            for j in range(i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[i], dp[j] + 1)
        return max(dp)
  • Version 2
class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        order = []
        for i in range(n):
            if len(order) == 0 or order[-1] < nums[i]:
                order.append(nums[i])
            else:
                index = bisect.bisect_left(order, nums[i])
                order[index] = nums[i]
        return len(order)

Reference

  1. https://leetcode.com/problems/longest-increasing-subsequence/

以上是关于Leetcode 300. Longest Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 300. Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence

leetcode300.Longest Increasing Subsequence

[leetcode-300-Longest Increasing Subsequence]

LeetCode 300. Longest Increasing Subsequence