In this Leetcode Coin Change 2 problem solution 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.

Leetcode Coin Change 2 problem solution


Problem solution in Python.

class Solution(object):
    def change(self, amount, coins):
        
        lst=[1]+[0]*amount
        
        for coin in coins:
            for i in range(coin,amount+1):
                lst[i]+=lst[i-coin] 
                
        return lst[-1]

Problem solution in Java.

public int change(int amount, int[] coins) {
        if(amount == 0){ // u can make amt = 0 in 1 way ie don't give any coins
            return 1; 
        }
        
        int [] dp = new int[amount+1]; 
        dp[0] = 1; 
        
        for(int coin : coins){ // u should loop coins over the amount to avoid permutations
            for(int i=1; i<dp.length; i++){
                if(i >= coin){
                    dp[i] += dp[i-coin]; 
                }
            }
        }
        
        return dp[amount]; 
    }


Problem solution in C++.

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        vector<vector<int>> dp(coins.size() + 1, vector<int> (amount + 1));
        dp[0][0] = 1;
        for(int i = 1; i < coins.size() + 1; i++){
            dp[i][0] = 1;
            for(int j = 1; j < amount + 1; j++){
                dp[i][j] = dp[i - 1][j] + (j >= coins[i-1] ? dp[i][j - coins[i - 1]] : 0);
            }
        }
        return dp[coins.size()][amount];
    }
};