美文网首页
LeetCode每日一题: 322. 零钱兑换

LeetCode每日一题: 322. 零钱兑换

作者: pao哥 | 来源:发表于2019-11-06 22:25 被阅读0次

    322. 零钱兑换

    标签: 动态规划

    给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

    示例1:
    输入: coins = [1, 2, 5], amount = 11
    输出: 3
    解释: 11 = 5 + 5 + 1

    示例2:
    输入: coins = [2], amount = 3
    输出: -1

    思路

    '''
    1. 观察到题目主要问题可以划分成规模更小子问题, 采用动态规划思想解题
    2. 先确定状态: 假设金额为i所需的最少硬币个数为counts[i]
        2.1 从最后一步考虑: counts[amount] = min(counts[amount-coins[0],counts[amount-coins[1]] ...])  + 1
        2.2 则原问题可分解成为更小的子问题
    3. 则我们可以确定其动态方程:counts[i] = min([counts[i-coins[j]] for j in coins]) + 1
    4. 我们需要确定起始条件和边界条件:
        起始条件: counts[0] = 0
        边界条件: i >= 0 
    5. 求解顺序: 从0到amount
    '''
    class Solution:
        def coinChange(self, coins: List[int], amount: int) -> int:
            costs = [-1] * (amount + 1)
            costs[0] = 0
    
            for i in range(1, amount + 1):
                lst = [costs[i-coin] for coin in coins if i-coin >= 0 and costs[i-coin]!= -1]
                costs[i] = min(lst) + 1 if lst else -1
    
            return costs[-1]                    

    相关文章

      网友评论

          本文标题:LeetCode每日一题: 322. 零钱兑换

          本文链接:https://www.haomeiwen.com/subject/oaxpbctx.html