https://leetcode.com/problems/coin-change/
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.
classSolution { Public: intDfsintAmount, vector<int>& coins, vector<int>&DP) { if(Amount = =0)return 0; if(Amount <0)returnInt_max; if(Dp[amount])returnDp[amount]; intMinchange =Int_max; for(intI=0; I<coins.size (); + +i) {intEachchange = DFS (amount-Coins[i], coins, DP); if(Eachchange = = Int_max) Minchange =min (Minchange, Int_max); ElseMinchange = min (minchange, Eachchange +1); } Dp[amount]=Minchange; returnDp[amount]; } intCoinchange (vector<int>& coins,intamount) { intn =coins.size (); if(n = =0&& amount >0)return-1; if(n = =0&& Amount = =0)return 0; Vector<int> dp (amount+1,0); Dp[amount]=dfs (amount, coins, DP); if(Dp[amount] = = Int_max)return-1; Else returnDp[amount]; }};
View Code
[email protected] [322] Coin Change (Dynamic programming)