zoukankan      html  css  js  c++  java
  • 动态规划_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)
  • 相关阅读:
    由浅入深——从ArrayList浅谈并发容器
    Lambda表达式
    JVM初体验
    Redis主从复制
    Redis事务
    Redis基本命令
    Redis概述与安装
    Linux之SSH免密登录
    源码安装Nginx以及用systemctl管理
    CentOS 7 :Failed to start IPv4 firewall with iptables.
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546716.html
Copyright © 2011-2022 走看看