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];
    }
};
相关推荐
怕浪猫3 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记3 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_34 小时前
二叉树の递归遍历
算法
All for pursuit.4 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉5 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
一只小小的芙厨6 小时前
【线性DP】
学习·算法·动态规划
奋发向前wcx7 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
罗湖老棍子8 小时前
C Looooops(信息学奥赛一本通- P1640)
算法·数论·同余·裴蜀定理·扩展欧几里得
Interview Aid11210 小时前
OpenAI SWE 面试流程
面试·职场和发展
我命由我1234510 小时前
Photoshop - Photoshop 使用对齐功能定位元素
学习·职场和发展·产品运营·求职招聘·职场发展·产品经理·学习方法