#!/usr/bin/python# -*- coding: utf-8 -*-'''
Combination Sum IV
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.
'''classSolution(object):
times = 0defcombinationSum4(self, nums, target):"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if length == 0:
return0
Solution.times = 0
nums.sort()
self.__combinationSum4(nums,length,target,0)
return Solution.times
def__combinationSum4(self,nums,length,target,sum):if sum == target:
Solution.times += 1return0if sum > target:
return0for i in range(0,length):
self.__combinationSum4(nums,length,target,sum + nums[i])
if __name__ == "__main__":
s = Solution()
print s.combinationSum4([1,2,4],32)
动态规划
classSolution(object):defcombinationSum4(self, nums, target):"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if length == 0:
return0
nums.sort()
dp = [0] * (target+1)
for i in range(target + 1):
for val in nums:
if val > i:
breakif val == i:
dp[i] += 1break
dp[i] += dp[i - val]
return dp[target]