Prompt
Given an array of positive integers representing coin denominations and a single non-negative integer n representing a target amount of money, write a function that\ returns the smallest number of coins needed
to make change for that target amount using the given coin denominations.
If it’s impossible to make change for the target amount, return -1 . Note that an unlimited amount of coins is at
your disposal.
Sample Input
n = 7
denoms = [1, 5, 10]
Sample Output
3 // 2 * 1 + 1* 5
Solution
import java.util.*;
class Program {
// O(nd) time | O(n) space
public static int minNumberOfCoinsForChange(int n, int[] denoms) {
int [] numOfCoins = new int[n + 1]; //A
Arrays.fill(numOfCoins, Integer.MAX_VALUE); //
numOfCoins[0] = 0;
int toCompare = 0;
for (int denom : denoms) {
for (int amount = 1; amount < numOfCoins.length; amount++) {
if (denom <= amount) {
if(numOfCoins[amount - denom] == Integer.MAX_VALUE) {
toCompare = Integer.MAX_VALUE;
} else {
toCompare = 1 + numOfCoins[amount - denom];
}
numOfCoins[amount] = Math.min(numOfCoins[amount], toCompare);
}
}
}
return numOfCoins[n] != Integer.MAX_VALUE ? numOfCoins[n] : -1;
}
}
# A
类似于硬币这种问题 考虑这种思路