LeetCode 题解工作台
最长递增子序列
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如, [3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的 子序列 。 示例 1: 输入: nums = [10,9,2,5,3,7,10…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示以 结尾的最长递增子序列的长度,初始时 $f[i] = 1$,答案为 的最大值。 对于 ,我们需要枚举 $0 \le j \lt i$,如果 $nums[j] \lt nums[i]$,则 $f[i] = \max(f[i], f[j] + 1)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 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))吗?
解题思路
方法一:动态规划
我们定义 表示以 结尾的最长递增子序列的长度,初始时 ,答案为 的最大值。
对于 ,我们需要枚举 ,如果 ,则 。
最后的答案即为 的最大值。
时间复杂度 ,空间复杂度 。其中 为数组长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.