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 <= coinsi <= 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];
    }
};
相关推荐
不会就选b22 分钟前
算法日常・每日刷题--<快排>4
算法
Keven_1128 分钟前
算法札记:树状数组的用途
数据结构·算法
用户6774371758135 分钟前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法
cpp_25011 小时前
P1540 [NOIP 2010 提高组] 机器翻译
数据结构·c++·算法·队列·noip·洛谷题解
晚笙coding1 小时前
LeetCode 98:验证二叉搜索树 —— 从局部判断到全局范围约束的递归思想
算法·leetcode·职场和发展
学计算机的计算基1 小时前
回溯算法下篇:四道经典题讲透约束剪枝、原地标记、预计算与状态压缩
java·笔记·算法
霸道流氓气质2 小时前
SpringBoot中实现告警判定算法-位报警与模拟量阈值-技术详解
spring boot·算法·jquery
行者全栈架构师2 小时前
混元 Hy3 Agent 实战:季度报告 3 小时变 40 分钟
算法·架构·代码规范
兰令水2 小时前
hot100【acm版】【2026.7.21打卡-java版本】
java·开发语言·算法·leetcode·面试
好好沉淀3 小时前
主键选择(自增 vs UUID vs 雪花算法)
java·算法