算法作业系列14——Coin Change

算法作业系列14

Coin Change

写在前面

争取一日一道算法题,大学也已经过了三年了,是时候正视一下自己的未来了。

题目

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.

思路

其实看到第一反应就是,这不是揹包问题吗?冥思苦想之下发现自己还是没办法记得揹包问题怎么写,因此上维基查了一下,再来动手写这道题。
其实思路很简单,只要想出来状态转移方程怎么写,剩下的就是很短的代码了,那我们就要想,怎么去把这道题转成规模更小的子问题呢?其实很简单,对于每一个数值,只需要减去一个可以交换的硬币面额,再递归求解就可以啦!具体状态转移方程如下:

dp(i) = min{dp(i - p(j))} j=0~n

那当你性质冲冲写完一个递归代码的时候,你会发现,超时了,为什么呢?我们想一下,每次递归都需要计算一下子问题,之前计算的结果没有被很好地保存下来,因此超时也是家常便饭啦。
那怎么解决呢?很简单,空间换时间即可,我们利用for循环,从最小规模算起,利用数组保存当前面额需要的最少组合,如果不能就算成-1,每一次更大规模的问题就以之前的小规模问题求解,这样就可以重复利用之前的结果啦。

参考代码

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        if (amount == 0) {
            return 0;
        }
        vector<int> dp(amount);
        for (int i = 1; i <= amount; i++) {
            dp[i - 1] = -1;
            for (int j = 0; j < coins.size(); j++) {
                if (coins[j] <= i && dp[i - coins[j] - 1] != -1 && (dp[i - 1] == -1 || dp[i - coins[j] - 1] < dp[i - 1])) {
                    dp[i - 1] = dp[i - coins[j] - 1] + 1;
                }
            }
        }
        return dp[amount - 1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章