leetcode:Coin Change

来源:互联网 发布:追星必备软件 编辑:程序博客网 时间:2024/06/14 08:31
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.


这是一道动态规划的题目,大意是说用他给定的几个面值的硬币,以最少的硬币个数凑出指定的数目。
最开始我想通过最传统的方式通过答案表一步一步推出最终结果,类似下面的例子:(num【i】表示凑成数字i所需的最少的硬币个数)
(以上述example 1为例)
首先num[1], num[2], num[5]等于1,随后从1开始检索num数组,若num[i]不等于amount + 1(即代表着可以通过硬币实现),就将他分别增加coin的面值,即加1,2,5。完成之后就i++,然后继续向下检索。直到i达到amount,此时若amount已经实现,则返回最小值,否则返回-1.
这是我最初的想法,但是在实现过程中出现了很多的问题,比如数组越界,参考别人的代码,发现可以在i处向前推,即dp[i] = min(dp[i], dp[i - coins[j]] + 1);这样就避免了数组越界的问题。代码如下:
int coinChange(vector<int>& coins, int amount) {
        int Max = amount + 1;
        vector<int> dp(amount + 1, Max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.size(); j++) {
                if (coins[j] <= i) {
                    dp[i] = min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }

原创粉丝点击