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.
You may assume that you have an infinite number of each kind of coin.
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
这题花了两个小时, 主要是memo怎么取的问题。
1. Top - Bottom
上图是本题的基本结构,可以看出这是一道深度优先搜索题, 递归找到最后等于0的最小深度, 所以一开始我是这么做的。
public int coinChange(int[] coins, int amount) {
return recursion(coins, amount);
}
private int recursion(int[] coins, int amount) {
if (amount == 0) {
return 0;
}
if (amount < 0) {
return -1;
}
int count = Integer.MAX_VALUE;
for (int i = 0; i < coins.length