LeetCode

来源:互联网 发布:网络监控黑屏是么原因 编辑:程序博客网 时间:2024/06/07 03:41

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.

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

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


你有数组中那些面额的纸币,问amount能否用纸币拼凑而成。

一个完全背包,纸币没有限量。时间复杂度O(namount),空间复杂度O(amount)

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

原创粉丝点击