322. Coin Change

本文提出了一种解决硬币找零问题的方法,使用贪心算法替代动态规划,通过将硬币按从大到小排序并尝试使用面额最大的硬币,直至总额达到目标金额。该算法不仅效率高,而且能够找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Actually, this problem could use greedy algorithm instead of dynamic programming and greedy algorithm is much faster. The basic idea is sort the coins array from the largest to the smallest and then try coin with the largest value until the total value is larger than "amount". If the total value cannot be equal to "amount" and then go back to the upper layer and try the second largest one... So the optimal answer always comes first.

class Solution {
public:
     int coinChange(vector<int>& coins, int amount) {
        sort(coins.begin(), coins.end(), greater<int>());

        int res = amount+1;
        ccHelper(amount, coins, 0, 0, res);
        return res==amount+1? -1: res;
    }
    void ccHelper(int amount, vector<int>&coins, int start, int step, int& res) {
        if (step+ceil(amount*1.0/coins[start])>=res) return;
        if (amount==0) {res=step; return;}
        for (int i=start; i<coins.size(); i++) {
            if (coins[i]<=amount) ccHelper(amount-coins[i], coins, i, step+1, res);
        }
    }
};

"greater" on the 4th line is an interesting and useful class. Please pay attention to it.

转载于:https://www.cnblogs.com/tekkaman-blade/p/7373412.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值