🧩Algo 动态规划

322. 零钱兑换

难度:🟡 Medium | 标签:动归、完全背包 | 状态:⬜ LeetCode 链接

思路

dp[i] = min(dp[i - c] + 1) for c in coins。 凑不出 amount 返回 -1。

代码

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<int> dp(amount + 1, amount + 1);
        dp[0] = 0;
        for (int i = 1; i <= amount; ++i) {
            for (int c : coins) {
                if (c <= i) dp[i] = min(dp[i], dp[i - c] + 1);
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
};

复杂度

  • 时间 O(amount · |coins|),空间 O(amount)

易错 / 回顾

  • 初始值 amount + 1 当哨兵,避免 INT_MAX 加 1 溢出
  • 与 518(凑零钱方案数)区分:那题求方案数,循环顺序不同
  • 贪心从大币种选不一定对([1, 5, 11],target=15)
Related · 动态规划