---
# System prepended metadata

title: Coin Change 2 _518
tags: [dp, leetcode, medium]

---


# Coin Change 2 _518

###### tags: `leetcode`,`dp`,`medium`




>ref: https://leetcode.com/problems/coin-change-2/
>
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

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

The answer is guaranteed to fit into a signed 32-bit integer.

>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
 

>Constraints:
1 <= coins.length <= 300
1 <= coins[i] <= 5000
All the values of coins are unique.
0 <= amount <= 5000



>1. 每種幣值需loop一次amount數量+1的陣列 時間需要 O\(N\*M\)
>2. 考慮成,單用特定一種幣值組出大小為總和的array記憶,後疊加
>疊加思考方式為 該幣值m本身會使count[m]+1, 1的來源為count[0] 想成每當新幣值加入考慮 可視為總數為0的組合數加上一枚新幣值\(1\)的組合, 因此coins陣列的幣值無須經過排序

```java=
    public int change(int amount, int[] coins) {
        
        int[] count = new int[amount+1];
        
        count[0]=1;
        
        for(int coin:coins){
            for(int i=coin; i<=amount;i++){
                count[i]+=count[i-coin];
            }
        }
        
        return count[amount];
    }
```
    
    
    
