首页 > 其他 > 详细

[leetcode-322-Coin Change]

时间:2017-06-25 09:31:11      阅读:211      评论:0      收藏:0      [点我收藏+]

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]

原文:http://www.cnblogs.com/hellowooorld/p/7076108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!