Fork me on GitHub

硬币找零

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
Map<Integer,Integer> cache=new HashMap<>();
public int coinChange(int [] coins,int amount)
{
if(amount==0)
{
return 0;
}
if(cache.containsKey(amount))
return cache.get(amount);
int count=amount+1;
for(int coin:coins)
{
int cur=0;
if(coin<=amount)
{
int next=coinChange(coins,amount-coin) ;
if(next>=0)
{
cur=next+1;
}
}
if(cur>0)
{count=Math.min(count,cur);}

}
int res=(count==amount+1)?-1:count;
cache.put(amount,res);
return res;
}
}

钱聪 wechat
欢迎交流学习。
么么!