LeetCode 322: Coin Change (硬币找零, DP经典题)

  1. Coin Change
    Medium
    17.4K
    391
    Companies
    You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

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

Example 1:

Input: coins = [1,2,5], amount = 11

Output: 3

Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3

Output: -1

Example 3:

Input: coins = [1], amount = 0

Output: 0

Constraints:

1 <= coins.length <= 12

1 <= coins[i] <= 231 - 1

0 <= amount <= 104

解法1:动态规划。注意此题不可用贪婪法。比如coins = {1, 3, 4}, amount = 6. 用贪婪法得到{4, 1, 1}这种组合,但实际上最优解是{3,3}。

cpp 复制代码
class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        if (n == 0 || amount == 0) return 0;
        vector<int> dp(amount + 1, INT_MAX);
        for (int i = 1; i <= amount; i++) {
            for (auto j : coins) {
                if (i == j) dp[i] = 1;
                else if (i > j && dp[i - j] != INT_MAX) {
                    dp[i] = min(dp[i], dp[i - j] + 1);
                }
            }
        }
        if (dp[amount] == INT_MAX) return -1;
        return dp[amount];
    }
};
相关推荐
张张努力变强14 分钟前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发14 分钟前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩20 分钟前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao29 分钟前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波00736 分钟前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
HY小宝F40 分钟前
职场沟通的深层智慧:从对抗到协作的自我修炼
职场和发展
风暴之零1 小时前
变点检测算法PELT
算法
深鱼~1 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果1 小时前
【PTA】L1-019 谁先倒
数据结构·算法
梵刹古音1 小时前
【C语言】 指针基础与定义
c语言·开发语言·算法