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];
    }
};
相关推荐
ZPC82101 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82101 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David1 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱1 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone1 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩1 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
蜡笔小马2 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237172 小时前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝2 小时前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
qq_459234422 小时前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评