#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.
#类似走楼梯:nums = [1,2,3], target = 4
#1有一种组合,2有两种组合,3有四种组合((-1后的组合)+ (-2后的组合)+ 本身正好-3 == 0)=1的组合+2的组合+1)
#同理,4的组合 = (4-1)的组合 + (4-2)的组合 + (4-3)的组合 = 1+2+4 = 7
#用递归写虽然很简单,但是递归的时间复杂度真的很垃圾,能不用尽量不用吧
class Solution(object):
def combinationSum4(self, nums, target):
nums, combs = sorted(nums), [1] + [0] * (target)
for i in range(target + 1):
for num in nums:
if num > i: break
if num == i: combs[i] += 1
if num < i: combs[i] += combs[i - num]
return combs[target]