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.
給出一個全為正整數(shù)且無重復數(shù)字的數(shù)組,找出加起來是一個正整數(shù)目標值的方法個數(shù)
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.
這道題可以用dfs+記憶化解決,但是我這里用dp來解決。思路為:既然target是數(shù)組中數(shù)字的組合,target - nums[i]和target有一定的關系。假設dp[i]為數(shù)組的元素加起來為i的方法個數(shù),遞推關系式為:dp[target] = sum(dp[target - nums[i]]),即把加上每個nums的元素到達target的方法數(shù)(dp[target - nums[i]])相加的總和就是數(shù)組元素加起來為target的方法總數(shù)
class Solution(object): def combinationSum4(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ dp = [1] + [0] * target for index in range(target + 1): # 把每個target - nums[i]的方法數(shù)相加 for n in nums: # nums的當前元素要小于target,否則拋棄該元素 if n <= index: dp[index] += dp[index - n] return dp[target]
|
新聞熱點
疑難解答