LeetCode377:Combination Sum IV(動態規劃)
阿新 • • 發佈:2018-11-29
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?
LeetCode:連結
這道題是說給的陣列中全是整數且沒有重複,但是每個數字可以重複使用,讓給出組合的總數,就不用給出所有的排列。沿用回溯的方法當然可以啦,然後求個result的長度就行了。But他是會超時的,這就是我說的給出有多少種的時候就用動態規劃
我們需要一個一維陣列dp,其中dp[i]表示目標數為i的解的個數,然後我們從1遍歷到target,對於每一個數i,遍歷nums陣列,如果i>=x, dp[i] += dp[i - x]。這個也很好理解,比如說對於[1,2,3] 4,這個例子,當我們在計算dp[3]的時候,3可以拆分為1+x,而x即為dp[2],3也可以拆分為2+x,此時x為dp[1],3同樣可以拆為3+x,此時x為dp[0],我們把所有的情況加起來就是組成3的所有情況了。
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 num in nums: if i >= num: dp[i] += dp[i-num] return dp[target] a = Solution() print(a.combinationSum4([1,2,3], 4))