1. 程式人生 > >[leetcode-322-Coin Change]

[leetcode-322-Coin Change]

當前 compute col any nom for .cn program tar

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:
coins = [1, 2, 5], amount = 11


return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

Note:
You may assume that you have an infinite number of each kind of coin.

思路:

參考自:http://www.cnblogs.com/grandyang/p/5138186.html

對於求極值問題,我們還是主要考慮動態規劃Dynamic Programming來做,我們維護一個一維動態數組dp,其中dp[i]表示錢數為i時的最小硬幣數的找零,遞推式為:

dp[i] = min(dp[i], dp[i - coins[j]] + 1);

其中coins[j]為第j個硬幣,而i - coins[j]為錢數i減去其中一個硬幣的值,剩余的錢數在dp數組中找到值,然後加1和當前dp數組中的值做比較,取較小的那個更新dp數組。

int cointChange(vector<int>& coins,int amount)
  {
    vector<int>dp(amount+1,amount+1);
    dp[0] = 0;
    for(int i = 1;i<=amount;i++)
    {
       for(int j =0;j<coins.size();j++)
       {
     
if(coins[j]<=i)dp[i] = min(dp[i-coins[j]]+1,dp[i]); } } return dp[amount]>amount ? -1: dp[amount]; }

[leetcode-322-Coin Change]