LeetCode 题解工作台

组合总和 Ⅳ

给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素排列的个数。 题目数据保证答案符合 32 位整数范围。 示例 1: 输入: nums = [1,2,3], target = 4 输出: 7 解释: 所有可能的组合…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们定义 表示总和为 的元素组合的个数,初始时 $f[0] = 1$,其余 $f[i] = 0$。最终答案即为 。 对于 ,我们可以枚举数组中的每个元素 ,如果 $i \ge x$,则 $f[i] = f[i] + f[i - x]$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 不同 整数组成的数组 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 <= 200
  • 1 <= nums[i] <= 1000
  • nums 中的所有元素 互不相同
  • 1 <= target <= 1000

 

进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?

lightbulb

解题思路

方法一:动态规划

我们定义 f[i]f[i] 表示总和为 ii 的元素组合的个数,初始时 f[0]=1f[0] = 1,其余 f[i]=0f[i] = 0。最终答案即为 f[target]f[target]

对于 f[i]f[i],我们可以枚举数组中的每个元素 xx,如果 ixi \ge x,则 f[i]=f[i]+f[ix]f[i] = f[i] + f[i - x]

最后返回 f[target]f[target] 即可。

时间复杂度 O(n×target)O(n \times target),空间复杂度 O(target)O(target)。其中 nn 为数组的长度。

1
2
3
4
5
6
7
8
9
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]
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

组合总和 Ⅳ题解:状态·转移·动态规划 | LeetCode #377 中等