322. Coin Change(Leetcode每日一题-2020.03.08)

Problem

You are given coins of different denominations and a total amount of money amount. Write a function to compute 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.

Note:
You may assume that you have an infinite number of each kind of coin.

Example1

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example2

Input: coins = [2], amount = 3
Output: -1

Solution

2020-3-8,看到这一题的第一反应时回溯,但是遇到了溢出和超时的问题。
这一题实际上是动态规划。

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        if(amount == 0)
            return 0;

        //dp[i]表示兑换i需要的钱最少需要的硬币数
        vector<int> dp(amount+1,amount+1);

        dp[0] = 0;
        for(int i = 0;i<amount+1;++i)
        {
            for(int j = 0;j<coins.size();++j)
            {
                if(i >= coins[j])
                {
                    dp[i] = min(dp[i],dp[i - coins[j]] + 1);
                }
            }
        }

        return dp[amount] > amount? -1:dp[amount];

    }
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104729123