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];
    }
};
相关推荐
GreenTea36 分钟前
OpenAI Agents API 上手实测:一次调用把整个 agent loop 甩给 OpenAI
前端·后端·算法
深圳满意度咨询2 小时前
医院满意度数字化测评系统:从数据采集到智能决策的技术实践
算法
xiangyun612 小时前
【408数据结构 08】队列:循环队列判空判满,408年年考,一次讲清
c语言·开发语言·数据结构·c++·算法
xiangyun612 小时前
【408数据结构 06】双链表、循环链表、静态链表
c语言·开发语言·数据结构·c++·算法
June bug4 小时前
【HCIA- AI(正课)】3.1.人工智能业务流程
职场和发展
302wanger4 小时前
推荐下我的两个AI信息源
算法
索尔~古德曼4 小时前
CF——错题的集合
算法
SL_staff4 小时前
JVS-Logic:从页面配置工具到企业级业务逻辑中枢的技术演进
java·算法·全栈
陌シ未央ゞ5 小时前
基于BM25算法和RRF实现的混合索引(java版)
人工智能·spring boot·后端·算法
renhongxia15 小时前
数字孪生不止在工厂:能源、医疗与农业
人工智能·深度学习·算法·机器学习·数字孪生