problem
518. 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
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
wrong approach
class Solution {
public:
vector<vector<int>> dp;
int rec(int amount, int depth, vector<int>& coins){
if(amount < 0)return 0;
if(amount == 0){
// if(dp[depth] == 0)
// return dp[depth] = 1;
// else return 0;
return 1;
}
//if(dp[depth + amount/coins[0]] == 1) return 0;
int res = 0;
for(auto coin : coins){// iterate through all kinds of coin
res += rec(amount - coin, depth+1, coins);// tmp = subtree's return
}
return res;
}
int change(int amount, vector<int>& coins) {
if(coins.size() == 0) return 0;
sort(coins.begin(), coins.end());
dp = vector<int>((amount/coins[0]) + 1, 0);
return rec(amount, 0, coins);
}
};
approach memorize dp
class Solution {
public:
vector<vector<int>> dp;
int solve(vector<int>& coins,int m,int n){
if(m==-1 && n>0)
return 0;
if(n==0)
return 1;
if(n<0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
return dp[m][n]=solve(coins,m,n-coins[m])+solve(coins,m-1,n);
}
int change(int amount, vector<int>& coins) {
dp = vector<vector<int>>(coins.size(), vector<int>(amount+1, -1));
return solve(coins,coins.size()-1,amount);
}
};