|
| 1 | +// Source : https://leetcode.com/problems/coin-change-2/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-03-18 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given coins of different denominations and a total amount of money. Write a function to |
| 8 | + * compute the number of combinations that make up that amount. You may assume that you have infinite |
| 9 | + * number of each kind of coin. |
| 10 | + * |
| 11 | + * Example 1: |
| 12 | + * |
| 13 | + * Input: amount = 5, coins = [1, 2, 5] |
| 14 | + * Output: 4 |
| 15 | + * Explanation: there are four ways to make up the amount: |
| 16 | + * 5=5 |
| 17 | + * 5=2+2+1 |
| 18 | + * 5=2+1+1+1 |
| 19 | + * 5=1+1+1+1+1 |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: amount = 3, coins = [2] |
| 24 | + * Output: 0 |
| 25 | + * Explanation: the amount of 3 cannot be made up just with coins of 2. |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * |
| 29 | + * Input: amount = 10, coins = [10] |
| 30 | + * Output: 1 |
| 31 | + * |
| 32 | + * Note: |
| 33 | + * |
| 34 | + * You can assume that |
| 35 | + * |
| 36 | + * 0 <= amount <= 5000 |
| 37 | + * 1 <= coin <= 5000 |
| 38 | + * the number of coins is less than 500 |
| 39 | + * the answer is guaranteed to fit into signed 32-bit integer |
| 40 | + * |
| 41 | + ******************************************************************************************************/ |
| 42 | +class Solution { |
| 43 | +public: |
| 44 | + int change(int amount, vector<int>& coins) { |
| 45 | + return change_dp(amount, coins); |
| 46 | + return change_recursive(amount, coins); // Time Limit Error |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + int change_recursive(int amount, vector<int>& coins) { |
| 51 | + int result = 0; |
| 52 | + change_recursive_helper(amount, coins, 0, result); |
| 53 | + return result; |
| 54 | + } |
| 55 | + |
| 56 | + // the `idx` is used for remove the duplicated solutions. |
| 57 | + void change_recursive_helper(int amount, vector<int>& coins, int idx, int& result) { |
| 58 | + if (amount == 0) { |
| 59 | + result++; |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + for ( int i = idx; i < coins.size(); i++ ) { |
| 64 | + if (amount < coins[i]) continue; |
| 65 | + change_recursive_helper(amount - coins[i], coins, i, result); |
| 66 | + } |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + int change_dp(int amount, vector<int>& coins) { |
| 71 | + vector<int> dp(amount+1, 0); |
| 72 | + dp[0] = 1; |
| 73 | + for (int i=0; i<coins.size(); i++) { |
| 74 | + for(int n=1; n<=amount; n++) { |
| 75 | + if (n >= coins[i]) { |
| 76 | + dp[n] += dp[n-coins[i]]; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return dp[amount]; |
| 82 | + } |
| 83 | +}; |
| 84 | + |
0 commit comments