Leetcode 518: Coin Change 2
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
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
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
1 public class Solution { 2 public int Change(int amount, int[] coins) { 3 if (amount < 0) return -1; 4 5 // dp[i] means the minimal coins to get that amount 6 var dp = new int[amount + 1]; 7 8 // dp[0] means there is one way to make up 0 9 dp[0] = 1; 10 11 /* 12 // NOTE: this doesn't work due to duplicate 13 14 dp[0] = 1 15 dp[1] = 1 16 dp[2] = 2 17 dp[3] = 3 18 dp[4] = 5 19 20 2: 1 1 21 2: 2 22 23 3: 1 : 1 : 1 24 3: 2 : 1 25 3: 1 : 2 26 27 for (int i = 1; i < dp.Length; i++) 28 { 29 for (int j = 0; j < coins.Length; j++) 30 { 31 if (i - coins[j] >= 0) 32 { 33 dp[i] += dp[i - coins[j]]; 34 } 35 } 36 } 37 */ 38 39 for (int j = 0; j < coins.Length; j++) 40 { 41 for (int i = 1; i < dp.Length; i++) 42 { 43 if (i - coins[j] >= 0) 44 { 45 dp[i] += dp[i - coins[j]]; 46 } 47 } 48 } 49 50 return dp[amount]; 51 } 52 }