[leetcode] 322. Coin Change 零钱兑换-动态规划

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:
You may assume that you have an infinite number of each kind of coin.

分析

题目的意思是:
给你一定币值的硬币(数量不限制),问用最小的钱数凑齐给定的值。

  • dp[i]表示凑齐钱数i所需要的最小硬币数,dp[i]就是当前i最小钱数和i-coin的最小硬币数的最小值。

即:dp[i]=min(dp[i-coin]+1,dp[i]);

代码

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<int> dp(amount+1,0x7ffffffe);
        dp[0]=0;
        for(auto coin:coins){
            for(int i=1;i<=amount;i++){
                if(i-coin>=0){
                    dp[i]=min(dp[i-coin]+1,dp[i]); 
                }
            }
        }
        return dp[amount]==0x7ffffffe ? -1: dp[amount];
    }
};

代码二(python)

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp=[float('inf')]*(amount+1)
        dp[0]=0
        for coin in coins:
            for x in range(coin,amount+1):
                dp[x]=min(dp[x],dp[x-coin]+1)
        if(dp[amount]!=float('inf')):
            return dp[amount]
        return -1

代码三 Python

思路跟代码二一样,都是dp数组初始化一个最大的值,然后递推求最小。

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp =[amount+1]*(amount+1)

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

代码四

用二维数据好理解一下,所以我也实现了一下二维数据的解法。

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [[float('inf')]*(amount+1) for i in range(len(coins)+1)]
        for i in range(len(coins)+1):
            dp[i][0]=0
        for i in range(1,len(coins)+1):
            for j in range(1,amount+1):
                if j-coins[i-1]>=0:
                    dp[i][j]=min(dp[i-1][j],dp[i][j-coins[i-1]]+1)
                else:
                    dp[i][j]=dp[i-1][j]
        if dp[len(coins)][amount]==float('inf'):
            return -1
        return dp[len(coins)][amount]

参考文献

leetcode 322. Coin Change-硬币交换|动态规划
leetcode solution

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值