題目如下:
定不同面額的硬幣 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]; }
好了,硬幣兌換的問題就解決啦!