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]。
1 class Solution(object): 2 def combinationSum4(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 dp = [0]*(target + 1) 9 dp[0] = 1 10 for i in range(target+1): 11 for n in nums: 12 if i + n <= target: 13 dp[i+n] += dp[i] 14 return dp[-1] 15
时间: 2024-11-01 20:16:17