标签:The else dash ash public cti amount code diff
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
Example 1:
Input: coins =[1, 2, 5]
, amount =11
Output:3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins =[2]
, amount =3
Output: –1
想法:采用动态规划,状态转移表达式为result[amount]=result[amount-coins]+1;
class Solution { public: int coinChange(vector<int>& coins, int amount) { int len = coins.size(); vector<int> result(amount+1); result[0] = 0; int max = INT_MAX; for(int i = 1 ; i <= amount ;i++ ){ result[i] = max; for(int j = 0 ; j < coins.size() ; j++){ if(i >= coins[j] && result[i-coins[j]]!= max && result[i-coins[j]]+1<result[i]){ result[i] = result[i-coins[j]] + 1; } } } if(result[amount] == max){ return -1; }else{ return result[amount]; } } };
标签:The else dash ash public cti amount code diff
原文地址:https://www.cnblogs.com/tingweichen/p/9973829.html