加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

322_零钱兑换-python

发布时间:2020-12-20 11:00:41 所属栏目:Python 来源:网络整理
导读:动态规划问题,稍后更新思路 class Solution(object): def coinChange(self,coins,amount): """ :type coins: List[int] :type amount: int :rtype: int """ INF = float('inf') dp = [] N = len(coins) for _ in range(N): tmp = [INF] * (amount+1) tmp[0]

动态规划问题,稍后更新思路

class Solution(object):
    def coinChange(self,coins,amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        INF = float('inf')
        dp = []
        N = len(coins)
        for _ in range(N):
            tmp = [INF] * (amount+1)
            tmp[0] = 0
            dp.append(tmp)

        for j in range(1,amount+1):
            if j >= coins[0] and dp[0][j-coins[0]] != INF:
                dp[0][j] = dp[0][j-coins[0]] + 1
        for i in range(1,N):
            for j in range(1,amount+1):
                if j >= coins[i]:
                    dp[i][j] = min(dp[i - 1][j],dp[i][j-coins[i]] + 1)
                else:
                    dp[i][j] = dp[i - 1][j]
        return dp[len(coins)- 1][amount] if dp[N-1][amount] != INF else -1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读