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
.
Example 1:
coins = [1, 2, 5]
, amount = 11
return 3
(11 = 5 + 5 + 1)
Example 2:
coins = [2]
, amount = 3
return -1
.
Note:
You may assume that you have an infinite number of each kind of coin.
很经典的题目了,但是搞起来还是有点费力的。
这题是要求全局最优,用贪心搞得话数据好一点是过不了的,唯有用dp搞了
最重要的一点是在状态转移的时候 先要判断 ret[i-coins[j]]是否可以找开,找不开就不搞。
Ps.可能可以简化一下代码,但是当时没想太多就写了
public class Solution { public int coinChange( int[] coins, int amount ) { if(amount==0) return 0; int[] ret = new int[ amount + 1 ]; for( int i = 1; i <= amount; i++ ) { int min = i; for( int j = 0; j < coins.length; j++ ) { if( i >= coins[ j ] ) { if(i==coins[j]){ ret[i] = 1; } //这里判断一下是否可以找开 else if(ret[i-coins[j]]>0){ if(i%coins[j]==0){ ret[i] = Math.min(ret[i-coins[j]]+1,i/coins[j]); }else{ ret[i] = ret[i-coins[j]] +1; } if(ret[i]<min){ min = ret[i]; } ret[i] = min; }else{ ret[i-coins[j]]=-1; } } } } if(ret[amount]==0) return -1; return ret[ amount ]; } public static void main( String[] args ) { Solution s = new Solution(); int[] coins = new int[] { 1,2 }; int amount = 3; System.out.println( s.coinChange( coins, amount ) ); } }
时间: 2024-10-26 00:34:28