LeetCode 题解工作台
和为目标值的最长子序列的长度
给你一个下标从 0 开始的整数数组 nums 和一个整数 target 。 返回和为 target 的 nums 子序列中,子序列 长度的最大值 。如果不存在和为 target 的子序列,返回 -1 。 子序列 指的是从原数组中删除一些或者不删除任何元素后,剩余元素保持原来的顺序构成的数组。 示例 …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示前 个数中选取若干个数,使得这若干个数的和恰好为 的最长子序列的长度。初始时 ,其余位置均为 。 对于 ,我们考虑第 个数 ,如果不选取 ,那么 ;如果选取 ,那么 ,其中 $j\ge x$。因此我们有状态转移方程:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 target 。
返回和为 target 的 nums 子序列中,子序列 长度的最大值 。如果不存在和为 target 的子序列,返回 -1 。
子序列 指的是从原数组中删除一些或者不删除任何元素后,剩余元素保持原来的顺序构成的数组。
示例 1:
输入:nums = [1,2,3,4,5], target = 9 输出:3 解释:总共有 3 个子序列的和为 9 :[4,5] ,[1,3,5] 和 [2,3,4] 。最长的子序列是 [1,3,5] 和 [2,3,4] 。所以答案为 3 。
示例 2:
输入:nums = [4,1,3,2,1,5], target = 7 输出:4 解释:总共有 5 个子序列的和为 7 :[4,3] ,[4,1,2] ,[4,2,1] ,[1,1,5] 和 [1,3,2,1] 。最长子序列为 [1,3,2,1] 。所以答案为 4 。
示例 3:
输入:nums = [1,1,5,4,5], target = 3 输出:-1 解释:无法得到和为 3 的子序列。
提示:
1 <= nums.length <= 10001 <= nums[i] <= 10001 <= target <= 1000
解题思路
方法一:动态规划
我们定义 表示前 个数中选取若干个数,使得这若干个数的和恰好为 的最长子序列的长度。初始时 ,其余位置均为 。
对于 ,我们考虑第 个数 ,如果不选取 ,那么 ;如果选取 ,那么 ,其中 。因此我们有状态转移方程:
最终答案为 ,如果 ,则不存在和为 的子序列,返回 。
时间复杂度 ,空间复杂度 。其中 为数组长度,而 为目标值。
我们注意到 的状态只与 有关,因此我们可以优化掉第一维,将空间复杂度优化到 。
class Solution:
def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int:
n = len(nums)
f = [[-inf] * (target + 1) for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(target + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = max(f[i][j], f[i - 1][j - x] + 1)
return -1 if f[n][target] <= 0 else f[n][target]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate explain the dynamic programming approach effectively?
- question_mark
Do they recognize that backtracking is only used if DP doesn't yield the solution?
- question_mark
Are they able to optimize the space complexity by using a greedy approach or a reduced state transition table?
常见陷阱
外企场景- error
Failing to correctly handle edge cases where no subsequence exists that sums to the target.
- error
Not understanding the necessity of updating the dynamic programming state in a way that ensures the subsequence is as long as possible.
- error
Using brute-force methods instead of dynamic programming, leading to inefficient solutions.
进阶变体
外企场景- arrow_right_alt
What if the target value is zero? The solution would need to handle the edge case where an empty subsequence is a valid answer.
- arrow_right_alt
What if the input array is sorted? Could that lead to potential optimizations in the DP approach?
- arrow_right_alt
How does this approach change if elements in nums can be negative?