Leetcode 377. Combination Sum IV

时间:2021-10-13 17:44:31

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4 The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7.

Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?

例子:[1,2,3,5,6], target = 8。dp[8] 意为有多少种方式可以生成8。

例如: 8=1(in nums) + 7 = 2(in nums) + 5 = 3(in nums) + 4= 5(in nums) + 3 = 6(in nums) + 2。 所以dp[8] = dp[7] + dp[5] + dp[4] + dp[3] + dp[2]。

5=5(in nums) + 0 = 3(in nums) + 2 = 2(in nums) + 3 = 1(in nums) +4。 所以dp[5] = dp[0] + dp[2] + dp[4] + dp[4]。

 class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0]*(target + 1)
dp[0] = 1
for i in range(target+1):
for n in nums:
if i + n <= target:
dp[i+n] += dp[i]
return dp[-1]