# coding=utf8
# 递归
class Solution1(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or target <= 0:
return 0
return self.tryCombination(nums,target)
#组合遍历
def tryCombination(self,nums,target):
if target == 0:
return 1
res = 0
for item in nums:
if target - item >= 0:
res += self.tryCombination(nums,target-item)
return res
# s = Solution1()
#
# nums = [1,2,3]
# target = 4
#
#
# print s.combinationSum4(nums,target)
# 记忆化递归
class Solution2(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or target <= 0:
return 0
self.memo = [-1 for i in range(target+1)]
return self.tryCombination(nums,target)
def tryCombination(self,nums,target):
if self.memo[target] != -1:
return self.memo[target]
# self.memo[0] -1
if target == 0:
return 1
res = 0
for item in nums:
if target - item >= 0:
res += self.tryCombination(nums,target-item)
self.memo[target] = res
return res
# s = Solution2()
#
# nums = [1,2,3]
# target = 4
#
#
# print s.combinationSum4(nums,target)
# 动态规划
class Solution3(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or target <= 0:
return 0
memo = [-1 for i in range(target+1)]
memo[0] = 1
for i in range(1,target+1):
memo[i] = 0
for item in nums:
if i - item >= 0:
memo[i] += memo[i-item]
return memo[target]
s = Solution3()
nums = [1,2,3]
target = 4
print s.combinationSum4(nums,target)
转载于:https://www.cnblogs.com/lux-ace/p/10546716.html