零钱兑换

零钱兑换,第1张

概述题目 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1: 输入: coins = , amount = 输出: 解释: 11 = 5 + 5 + 1[1, 2, 5]113 示例 2: 输入: coins = , amount = 输出: -1[2]3 说明:

题目

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

示例 1:

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

示例 2:

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

说明:
你可以认为每种硬币的数量是无限的。

代码

思路:动态规划假设conis={c1,c2,...},那么f(n)=min{f(n-c1),f(n-c2),...}+1,遍历的过程中用数组记录计算过的值。public class 零钱兑换 {    public static int coinChange(int[] coins,int amount) {        int[] count=new int[amount+1];        for(int i:coins){            if(i<=amount){                count[i]=1;//面值比总和还大的肯定用不上            }        }        return solve(coins,amount,count);    }    public static int solve(int[]coins,int amount,int[] count){        if(amount<0){            return -1;        }        if(amount==0){            return 0;        }        if(count[amount]!=0){            return count[amount];//返回计算过的值        }        int min=Integer.MAX_VALUE;        int temp;        for(int i:coins){            temp=solve(coins,amount-i,count);            if(temp!=-1&&min>temp){                min=temp;            }        }        return count[amount]=min!=Integer.MAX_VALUE?min+1:-1;    }    public static voID main(String[] args){        int[] coins={1,5};        int amount=11;        System.out.println(coinChange(coins,amount));    }}
总结

以上是内存溢出为你收集整理的零钱兑换全部内容,希望文章能够帮你解决零钱兑换所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1026769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存