leetcode--322--coins change

转载请注明出处:

http://write.blog.csdn.net/postedit/77619703


问题:

https://leetcode.com/problems/coin-change/description/


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.

 

C++版1:

https://discuss.leetcode.com/topic/32519/6-7-lines-2-ways/2

 

int coinChange(vector<int>& coins, int amount) {
    vector<int> dp(amount+1, amount+1);
    dp[0] = 0;
    for (int a = 1; a<= amount; a++)
        for (int c : coins)
            if (c <= a)
                dp[a] = min(dp[a], dp[a-c] + 1);
    return dp.back() > amount ? -1 : dp.back();
}

C++版2:


int coinChange(vector<int>& coins, int amount) {
    vector<int> dp(amount+1, amount+1);
    need[0] = 0;
    for (int c : coins)
        for (int a=c; a<=amount; a++)
            dp[a] = min(dp[a],dp[a-c] + 1);
    return dp.back() > amount ? -1 : dp.back();
}



思路:


这题题是典型的一维动态规划问题,答案不难理解


dp[i]是满足总金额为 i的最少钱币数。核心思路是:


 need[a] = min( dp[a], dp[a-c] + 1 )


举个例子,假设可供选择的钱币有1、5、10、20、50元,那么 255 元需要最少的钱币数如下:

 

min1 = dp[ 255 - 1 ] + 1;

min2 = dp[ 255  -5 ] + 1;

min3 = dp[ 255 - 10 ] + 1;

min4 = dp[ 255 - 20 ] + 1;

min5 = dp[ 255 - 50 ] + 1;

dp[ 255 ] =  min(min1,  min2,  min3,  min4,  min5);


这里有个细节问题的是,coins 可以放在外层循环中,速度可能更快,因为coins 相对 amount 要少的多,


放在外层的话,内层循环切换到外层循环的次数就少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值