• 动态规划_leetcode377


    # 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)
  • 相关阅读:
    [每日短篇] 1C
    项目Alpha冲刺 Day12
    项目Alpha冲刺 Day12
    [转载]MVC中单用户登录
    GitLab
    Git 版本控制
    Jenkins持续集成
    Jenkins安装
    Docker 网络基础原理
    java中内存的使用
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546716.html
Copyright © 2020-2023  润新知