Problem Description

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

Problem Link

Reference Video

https://www.youtube.com/watch?v=ruMqWViJ2_U&ab_channel=TECHDOSE

Code

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        
        int n = coins.size();
        int dp[n+1][amount+1];
        **sort(coins.begin(),coins.end());**
        
        // Upon changing the order of loops the ans won't change because
        // dp[i][j] = number of ways to get sum 'j' using 'first i' coins
					for(int i=0;i<=n;i++) {
            for(int j=0;j<=amount;j++) {
                
                if(!i&&!j)
                    dp[i][j] = 0;
                
                else if(!i&&j)
                    dp[i][j] = 0;
                
                else if(i&&!j)
                    dp[i][j] = 1;
                
                else if(j>=coins[i-1])
                    **dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]] ;**
                
                else
                     dp[i][j] = dp[i-1][j] ;
            }
        }
        return dp[n][amount];
    }
};

Space Optimized Version

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        
     int n = coins.size();
    
    vector<int> dp(amount+1,0);
    
    dp[0] = 1;
    
    // Note the order of the loops
    for(int j=0;j<n;j++)
    {
        for(int i=1;i<=amount;i++)
        {
            if(i>=coins[j])
            dp[i] = dp[i] + dp[i-coins[j]]; // getting amount i using first j coins 
        }
    }
    
    return dp[amount];
        
    }
};