zoukankan      html  css  js  c++  java
  • 动态规划_leetcode416

    # 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)
  • 相关阅读:
    SQL 函数以及SQL 编程
    查询练习(四十五道题)
    SQL server 高级查询
    SQL server 数据库 操作及简单查询
    T-SQL 语句
    SQL
    表单验证、实则表达式、事件
    视频插入代码
    插入地图
    网页布局小练
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546718.html
Copyright © 2011-2022 走看看