Leetcode #322:零钱兑换

Leetcode #322:零钱兑换

题目

题干

看题面:零钱兑换

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

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

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

示例

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

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

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

题解

思路:ans数组,存储当前index的钱应该用几个coins,主要思路就是,要么是当前index中存储的需要的硬币个数,要么是当前index值的amount需要当前ans[index]中存储的硬币个数,要么是ans[index-coins[i]]+1,这个是如果加上当前面值coins[i]的硬币时,那么当前amount就是index-coins[i],所以查看ans[index-coins[i]]中存储的硬币个数,然后加上当前这一枚硬币,就是amount为index时所需的硬币个数,取这两种可能中的最小值就是所需最少硬币个数。

递推方程

ans[i] = Math.min(ans[i],ans[i-coins[j]]+1)

图示
零钱兑换推演过程

Java

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] ans = new int[amount+1];
        Arrays.fill(ans,amount+1);
        ans[0] = 0;
        for(int j = 0;j<coins.length;j++){
            for(int i=1;i<ans.length;i++){
                if(i>=coins[j]){
                    ans[i] = Math.min(ans[i],ans[i-coins[j]]+1);
                }
            }
        }
        return ans[amount]>amount?-1:ans[amount];
    }
}

Python

class Solution:
    def __init__(self, coins: list, amount: int):
        self.coins = coins
        self.amount = amount

    def coin_change(self):
        # ans存储目标值为当前索引值时,需要面值硬币中当前位置之前的所有面值硬币个数
  # 如对于coins[1]=2,ans[7]=4存储目标值为7时需要"1""2"两面值个数,即3个"2" 1个"1"
  ans = [self.amount+1] * (self.amount+1)
        ans[0] = 0
  for j in range(len(self.coins)):
            for i in range(len(ans)):
                if i >= self.coins[j]:
                    ans[i] = min(ans[i], ans[i - self.coins[j]] + 1)
        if ans[self.amount] > self.amount:
            return -1
  else:
            return ans[self.amount]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值