LeetCode 题解工作台
组合总和 Ⅳ
给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素排列的个数。 题目数据保证答案符合 32 位整数范围。 示例 1: 输入: nums = [1,2,3], target = 4 输出: 7 解释: 所有可能的组合…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示总和为 的元素组合的个数,初始时 $f[0] = 1$,其余 $f[i] = 0$。最终答案即为 。 对于 ,我们可以枚举数组中的每个元素 ,如果 $i \ge x$,则 $f[i] = f[i] + f[i - x]$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素排列的个数。
题目数据保证答案符合 32 位整数范围。
示例 1:
输入:nums = [1,2,3], target = 4 输出:7 解释: 所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 请注意,顺序不同的序列被视作不同的组合。
示例 2:
输入:nums = [9], target = 3 输出:0
提示:
1 <= nums.length <= 2001 <= nums[i] <= 1000nums中的所有元素 互不相同1 <= target <= 1000
进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?
解题思路
方法一:动态规划
我们定义 表示总和为 的元素组合的个数,初始时 ,其余 。最终答案即为 。
对于 ,我们可以枚举数组中的每个元素 ,如果 ,则 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
f = [1] + [0] * target
for i in range(1, target + 1):
for x in nums:
if i >= x:
f[i] += f[i - x]
return f[target]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for familiarity with dynamic programming concepts, specifically state transition and bottom-up approaches.
- question_mark
Candidates should be able to explain the transition between states clearly, showing understanding of dynamic programming.
- question_mark
Candidates should also discuss space optimization techniques like reducing the DP array to a one-dimensional structure.
常见陷阱
外企场景- error
Forgetting that different orders of the same combination count as distinct.
- error
Incorrectly initializing or updating the DP array, leading to missing or incorrect combinations.
- error
Not considering edge cases such as when `nums` has no valid combinations for the target.
进阶变体
外企场景- arrow_right_alt
Changing the problem to disallow repeated elements in combinations.
- arrow_right_alt
Adding constraints where some numbers in `nums` can only be used a limited number of times.
- arrow_right_alt
Using a different set of operations, such as subtraction instead of addition, and adjusting the approach accordingly.