The original title link is here: https://leetcode.com/problems/coin-change/
Topic:
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
.
Exercises
DP problem. State transfer Dp[i] = Math.min (Dp[i], dp[i-coins[j]]+1).
Dp[i-coins[j]]+1 represents i-coins[j] with a minimum number of coin.
Time Complexity:o (Amount * coins.length). Space:o (amount).
AC Java:
1 Public classSolution {2 Public intCoinchange (int[] coins,intamount) {3 if(Amount = = 0){4 return0;5 }6 if(Coins = =NULL|| Coins.length = = 0 | | Amount < 0){7 return-1;8 }9 int[] DP =New int[Amount+1];Ten Arrays.fill (DP, integer.max_value); OneDp[0] = 0; A for(inti = 1; i<=amount; i++){ - for(intj = 0; j<coins.length; J + +){ - //I-coins[j] "out of bounds or dp[i-coins[j]" is the maximum value for I-COINS[J] cannot be represented by coin the if(I-coins[j] < 0 | | dp[i-coins[j]] = =integer.max_value) { - Continue; - } -Dp[i] = Math.min (Dp[i], dp[i-coins[j]]+1); + } - } + returnDp[amount] = = Integer.max_value? -1: Dp[amount]; A } at}
Leetcode Coin Change