227 - 377 组合总和 Ⅳ
题目
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例:
nums = [1, 2, 3] target = 4
所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1)
请注意,顺序不同的序列被视作不同的组合。
因此输出为 7。
进阶: 如果给定的数组中含有负数会怎么样? 问题会产生什么变化? 我们需要在题目中添加什么限制来允许负数的出现?
解答
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
if not nums or target <= 0:
return 0
dp = [1]+[0]*target
for i in range(1, target+1):
for num in nums:
if i >= num:
dp[i] += dp[i-num]
return dp[-1]
Runtime: 40 ms, faster than 80.63% of Python3 online submissions for Combination Sum IV.
Memory Usage: 13.1 MB, less than 100.00% of Python3 online submissions for Combination Sum IV.
Last updated
Was this helpful?