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.
Input: coins =[1,2,5], amount =11
Output:3
Explanation:11=5+5+1
Input: coins =[2], amount =3
Output:-1
Note:
You may assume that you have an infinite number of each kind of coin.
二、题解
方法一:递归
int min;publicintcoinChange(int[] coins,int amount){
COINS = coins;returndfs(amount);}privateintdfs(int amount){if(amount <0)return-1;if(amount ==0)return0;//因为对每一个硬币都穷举一遍,得出最小的兑换数,所以
min = Integer.MAX_VALUE;for(int coin : COINS){int n =dfs(amount - coin);if(n >=0)
min = Math.min(min, n +1);}return min == Integer.MAX_VALUE ?-1: min;}
复杂度分析
时间复杂度:O(),
空间复杂度:O(),
方法二:记忆化搜索
int[] memo = null;publicintcoinChange(int[] coins,int amount){
COINS = coins;returndfsWithMempfs(amount);}privateintdfsWithMemp(int amount){if(amount <0)return-1;if(amount ==0)return0;if(memo[amount-1]!=0)return memo[amount-1];int min = Integer.MAX_VALUE;for(int coin : COINS){int n =dfsWithMemp(amount-coin);if(n >=0&& n < min) min = n +1;}
memo[amount-1]= min == Integer.MAX_VALUE ?-1: min;return memo[amount-1];}