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:
Input:coins = [1, 2, 5], amount = 11output:3 explanation:11 = 5 + 5 + 1
Example 2:
Input:coins = [2], amount = 3Output: 1
Note:
You may assume so you have a infinite number of each kind of coin.
For a typical problem of dynamic programming, think about what a recursive relationship is. Suppose Dp[i] represents the number of coins that I need for so much money, then for each coin with a different face value coins[j], dp[i] = Dp[i-coins[j]] + 1. As long as you traverse the coins face value of the time to choose the minimum number of good, that is min (Dp[i], dp[i-coins[j] "+ 1). General situation to think about the initial situation. Dp[0] is obviously 0, do not need a coin composition of 0 yuan. And since in the recursion to use the Min, then all the values are initially amount + 1 can be, because the coins are positive, there is no need to have more than amount coins. If the final result is larger than amount (in fact, the problem does not say that amount will not be the maximum positive, otherwise the value will overflow produce an error, test case does not have this situation), prove that there is no way to form the face value, need to return-1. It is important to note that because I-coins[j] appears as an array subscript, obviously conis[j] cannot be larger than I am.
Java
classSolution { Public intCoinchange (int[] coins,intamount) { if(Coins = =NULL|| Coins.length = = 0 | | Amount <= 0)return0; int[] DP =New int[Amount + 1]; Arrays.fill (DP, amount+ 1); dp[0] = 0; for(intj = 0; J < Coins.length; J + +) for(inti = coins[j]; I <= amount; i++) Dp[i]= Math.min (Dp[i], Dp[i-coins[j]] + 1); returnDp[amount] > amount? -1: Dp[amount]; }}
(Java) Leetcode 322. Coin change--Coin Exchange