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
class Solution {
public long count(int coins[], int N, int sum) {
// code here.
long dp[][] = new long[N][sum+1];
for(long d[] : dp) Arrays.fill(d,-1);
return count(0,coins,sum,dp);
}
public long count (int i, int coins[], int sum,long dp[][]){
//base case
if(sum ==0) return 1;
if(i == coins.length-1){
if(sum%coins[i]==0) return 1;
return 0;
}
if(dp[i][sum]!=-1) return dp[i][sum];
long take = 0;
if(sum>=coins[i]){
take = count(i,coins,sum-coins[i],dp);
}
long dontTake = count(i+1,coins,sum,dp);
return dp[i][sum] = take+dontTake;
}
}
We can remove the stack space by using tabulation approach of dp
Top comments (0)