[leetcode] 322. 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.

解题过程:

看到这道题的第一反应就是动态规划。。但是很久没做过动态规划的题了,只记得01背包问题这样最基础的,乍一做起来还是想了很久这个递推式的。本来题目没说coins是递增序列,就习惯性先sort一下,后来仔细想了下好像不用排序也没问题,就注释掉了。

首先初始化存放i块钱需要最少硬币数的数组r,初始化的值要尽量大。然后递推式是r[i]=min(r[i],r[i-coins[j]]+1);      就是更新i块钱需要的硬币数,从r[i]和i减去一个硬币面值后的硬币数+1里选最小的一个值更新。到最后如果r[amount]的值还是99999,肯定大于amount时,说明是没有整形硬币数凑到amount的面值。return -1;

代码:

class Solution {
public:

    int coinChange(vector<int>& coins, int amount) {
        //sort(coins.begin(),coins.end());
        vector<int > r(amount+1,99999);
        r[0]=0;
        int i;
        for(i=1;i<=amount;i++)
            for(int j=0;j<coins.size();j++)
                if(i>=coins[j])
                {
                    r[i]=min(r[i],r[i-coins[j]]+1);
                }
        return r[amount]>amount? -1:r[amount];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值