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 分钟前
【无标题】
算法
无限进步_24 分钟前
【C语言】寻找数组中唯一不重复的元素
c语言·开发语言·算法
JuneXcy28 分钟前
C语言易错点大总结
c语言·嵌入式硬件·算法
范特西_43 分钟前
两个无重叠子数组的最大和
c++·算法
可触的未来,发芽的智生1 小时前
触摸未来2025.10.05:悟神经网络符号之伤,拥抱声音的宇宙
人工智能·python·神经网络·算法·架构
_bong1 小时前
python评估算法性能
数据结构·python·算法
Mr.Ja3 小时前
【LeetCode 热题 100】No.49—— 字母异位词分组(Java 版)
java·算法·leetcode·字母异位词分组
未知陨落3 小时前
LeetCode:99.下一个排列
算法·leetcode
2401_841495643 小时前
【数据结构】链栈的基本操作
java·数据结构·c++·python·算法·链表·链栈
Archie_IT3 小时前
「深入浅出」嵌入式八股文—P2 内存篇
c语言·开发语言·数据结构·数据库·c++·算法