322. Coin Change

来源:互联网 发布:姚明对奥尼尔数据 编辑:程序博客网 时间:2024/05/29 03:53

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.

这道题要求最少的硬币数,思路是显然的,通过已知硬币面额,一步一步往后推,知道所求的数额。如果按照这种方法,也就是比如example1,有1推出(1 + 1)、(1 + 2)、 (1 + 5)然后依次往后退,这样会有一个比较尴尬的问题就是数组越界,这个问题是在后期提交代码报错时才发现的,一时间也卡在这边,不知道要如何巧妙地避免这种情况。后来参考了答案代码,方知可以有9可以由(9 - 1)、(9 - 2)、(9 - 5)推出,这种思路确实是十分巧妙,值得学习。总的来说,其实就是一个数一个数往后推,直到目标数字。

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];
    }


原创粉丝点击