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];
    }
};
相关推荐
青云计划21 小时前
数据库的ID的另一种选择-雪花算法
数据库·算法
夏日听雨眠21 小时前
linux(线程,线程同步 方法 互斥锁 信号量 条件变量 )
linux·运维·算法
神经网络机器学习智能算法画图绘图21 小时前
基于改进的支持向量机多分类预测研究
算法·支持向量机·分类
阿Y加油吧21 小时前
两道经典算法题复盘:最长有效括号 & 不同路径
算法
炜宏资料库21 小时前
零碳园区绿电直供技术的挑战与解决方案
职场和发展·职场发展
晚风叙码21 小时前
一文吃透二叉树:前中后序遍历+节点数+树高+叶子节点(含完整源码)
数据结构·算法
迦南的迦 亚索的索21 小时前
机器学习_05_k-means算法
算法·机器学习·kmeans
ychqsq21 小时前
24.方案交付日
经验分享·职场和发展
happymaker062621 小时前
LeetCodeHot100——1.两数之和(详细解答)
java·数据结构·学习·算法
AI人工智能+电脑小能手21 小时前
【大白话说Java面试题 第60题】【JVM篇】第20题:垃圾收集算法和垃圾收集器有什么区别?
java·jvm·算法·面试