You is given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins so need to make up that amount. If that amount of cannot is 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 so you have a infinite number of each kind of coin.
Title Link: https://leetcode.com/problems/coin-change/
Title Analysis: Because the number is infinite, so it is a complete knapsack count problem, dp[i] means the minimum number required to close to I, DP initialized to infinity, dp[0] = 0
public class Solution {public
int coinchange (int[] coins, int amount) {
int[] dp = new Int[amount + 1];
Arrays.fill (DP, integer.max_value);
Dp[0] = 0;
for (int i = 0; i < coins.length; i + +) {for
(int j = 0; J <= Amount; j + +) {
int pre = j-coins[i];
if (pre >= 0 && Dp[pre] < Integer.max_value) {
Dp[j] = Math.min (Dp[j], Dp[pre] + 1);}}}
if (dp[amount] = = integer.max_value) {
return-1;
}
return dp[amount];
}
}