Leetcode 518 Coin Change 2

给定硬币面额和种类,给定总金额,问有多少种组合方法;

https://leetcode-cn.com/problems/coin-change-2/

Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
 
Note:
You can assume that
0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer

 
硬币金额=重量,背包=金额,dp记录组合数

 

这题注意点就是说,一般要存满背包(这里的是金额),我们一般要用MAX去初始化数组,但是这题不是
 

* 这里用0初始化可以直接当做0种方法

* 然后注意对于金额0,应该是有1种方法(就是什么都不装)(这里就能够让面额2硬币,对于金额2来说有d[2] = d[2]+d[2-2] = 1)

* 可以重复使用,内层递增循环

* 另外注意更新的时候 状态转移方程应该是d[v] = d[v] + d[v-coins[i]],d[v]是上一行的结果,d[v-coins[i]]是这一行左边的结果

 
如图

 

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        int dp[amount+1];
        fill(dp,dp+amount+1,0);
        dp[0] = 1;
        int n = coins.size();
        for(int i=0;i<n;i++){
            for(int j=coins[i];j<=amount;j++){
                dp[j] = dp[j]+dp[j-coins[i]];
            }
        }
        return dp[amount];
    }
};
posted @ 2020-03-30 16:10  种树人  阅读(169)  评论(0编辑  收藏  举报