leetcode322—Coin Change
Posted tingweichen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode322—Coin Change相关的知识,希望对你有一定的参考价值。
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]; } } };
以上是关于leetcode322—Coin Change的主要内容,如果未能解决你的问题,请参考以下文章