LeetCode 题解工作台

最长递增子序列

给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如, [3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的 子序列 。 示例 1: 输入: nums = [10,9,2,5,3,7,10…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示以 结尾的最长递增子序列的长度,初始时 $f[i] = 1$,答案为 的最大值。 对于 ,我们需要枚举 $0 \le j \lt i$,如果 $nums[j] \lt nums[i]$,则 $f[i] = \max(f[i], f[j] + 1)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。

子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7]子序列

 

示例 1:

输入:nums = [10,9,2,5,3,7,101,18]
输出:4
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。

示例 2:

输入:nums = [0,1,0,3,2,3]
输出:4

示例 3:

输入:nums = [7,7,7,7,7,7,7]
输出:1

 

提示:

  • 1 <= nums.length <= 2500
  • -104 <= nums[i] <= 104

 

进阶:

  • 你能将算法的时间复杂度降低到 O(n log(n)) 吗?
lightbulb

解题思路

方法一:动态规划

我们定义 f[i]f[i] 表示以 nums[i]nums[i] 结尾的最长递增子序列的长度,初始时 f[i]=1f[i] = 1,答案为 f[i]f[i] 的最大值。

对于 f[i]f[i],我们需要枚举 0j<i0 \le j \lt i,如果 nums[j]<nums[i]nums[j] \lt nums[i],则 f[i]=max(f[i],f[j]+1)f[i] = \max(f[i], f[j] + 1)

最后的答案即为 f[i]f[i] 的最大值。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n)O(n)。其中 nn 为数组长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        f = [1] * n
        for i in range(1, n):
            for j in range(i):
                if nums[j] < nums[i]:
                    f[i] = max(f[i], f[j] + 1)
        return max(f)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate can explain the differences between the O(n^2) and O(n log n) solutions.

  • question_mark

    Assess the candidate’s understanding of how binary search integrates with dynamic programming to optimize the problem.

  • question_mark

    Evaluate how well the candidate discusses space optimization and its impact on performance in practical scenarios.

warning

常见陷阱

外企场景
  • error

    Failing to recognize the need for binary search to reduce time complexity from O(n^2) to O(n log n).

  • error

    Not maintaining the correct relative order when constructing the LIS array, leading to incorrect results.

  • error

    Overcomplicating the solution with unnecessary optimizations when a simpler approach would suffice for smaller inputs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the longest decreasing subsequence (LDS) by reversing the input array and applying the LIS algorithm.

  • arrow_right_alt

    Determine the longest subsequence that does not allow adjacent elements to differ by more than a constant value.

  • arrow_right_alt

    Generalize to k-longest increasing subsequences instead of just one, which requires advanced dynamic programming techniques.

help

常见问题

外企场景

最长递增子序列题解:状态·转移·动态规划 | LeetCode #300 中等