LeetCode 322. 零钱兑换

leetcode acwing

动态规划 \(O(n)\)

和之前做的完全平方数比较像

image-20210105110746248

C++ 代码

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        if (coins.empty()) return -1;
        vector<int> f(amount + 1, 1e8);
        f[0] = 0;

        for (int i = 0; i <= amount; i ++)
            for (auto c : coins)
                if (i >= c) f[i] = min(f[i], f[i - c] + 1);

        if (f[amount] >= 1e8) f[amount] = -1;
        return f[amount];
    }
};
posted @ 2021-01-05 11:10  alexemey  阅读(42)  评论(0)    收藏  举报