题目如下:
定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
例子:
输入: coins =[1, 2, 5]
, amount =11
输出:3
解释: 11 = 5 + 5 + 1
输入: coins =[2]
, amount =3
输出: -1
首先可以很自然的想到用递归去解决这个问题,用递归去遍历各种兑换的可能性,在其中记录下需要硬币最少的次数,如 11可以被 11个一元硬币兑换,也可以由两个五元 一个一元3枚硬币兑换。
递归式的编写最重要的是结束条件,可以想到,在一次次循环中,当amount小于0时,代表着本次循环不能正确兑完硬币,需要主动递归结束,开始下次循环。当amount等于0时,代表本次可以正确兑换,
自动跳出循环。
public class CoinsWay { public static void main(String[] args) { // TODO Auto-generated method stub } int res=Integer.MAX_VALUE; public int coinChange(int[] coins, int amount) { if(coins.length==0){ return -1; } helper(coins,amount,0); if(res==Integer.MAX_VALUE){ return -1; } return res; } public void helper(int[] coins,int amount,int count){ if(amount<0){ return; } if(amount==0){ res=Math.min(res, count); } for(int i=0;i<coins.length;i++){ helper(coins, amount-coins[i], count+1); } } }
但是递归会让导致计算重复的节点,如 【1,2,3】 amount=11,会导致下图情况
我们对其进行优化,进行记忆化递归,记忆化递归就是将已运算的结果进行存储,如上图我们对剩9元进行存储,在下次遍历到剩9元硬币时就可以直接返回结果,不必再次遍历
public int coinChange2(int[] coins,int amount){ if(amount<1) return 0; return helper2(coins,amount,new int[amount]); } public int helper2(int[] coins,int amount,int[] res){ if(amount<0){ return -1; } if(amount==0) return 0; if(res[amount-1]!=0){ return res[amount-1]; } int min=Integer.MAX_VALUE; for(int i=0;i<coins.length;i++){ int ress=helper2(coins, amount-coins[i], res); if(ress>=0&&ress<min){ min=ress+1; } } res[amount-1]=min==Integer.MAX_VALUE?-1:min; return res[amount-1]; }
下面使用自底向上也就是动态规划,动态规划就是将前面计算的结果拿来给后面用,因此如何定义就是一个问题,在这个问题种,我们定义数组res【amount+1】,代表数组下标对应的硬币元数所需的最小个数
public int coinChange3(int[] coins,int amount){ if(coins.length==0) return -1; //res数组代表 数组下标所对应的硬币元数兑换需要最少的硬币数 如res[9]代表9元硬币时兑换所需最小硬币书 int[] res=new int[amount+1]; //0元硬币需要0个硬币兑换 res[0]=0; for(int i=0;i<res.length;i++){ int min=Integer.MAX_VALUE; for(int j=0;i<coins.length;j++){ if(i-coins[j]>=0&&res[i-coins[j]]<min){ min=res[i-coins[j]]+1; } } res[i]=min; } return res[amount]==Integer.MAX_VALUE?-1:res[amount]; }
好了,硬币兑换的问题就解决啦!