Coin Change 2

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have an infinite number of each kind of coin.

Example:

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

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int change(int mvector<int&coins)
{
    int n = coins.size();
    int dp[n + 1][m + 1];
    for (int i = 0i <= ni++)
        dp[i][0] = 1;
    for (int i = 1i <= mi++)
        dp[0][i] = 0;
    for (int i = 1i <= ni++)
    {
        for (int j = 1j <= mj++)
        {
            if (coins[i - 1] <= j)
                dp[i][j] = dp[i - 1][j] + dp[i][j - 
coins[i - 1]];
            else
                dp[i][j] = dp[i - 1][j];
        }
    }
    return dp[n][m];
}

int main()
{
    int amount = 5;
    vector<intcoins = {125};

    cout << change(amountcoins);

    return 0;
}


No comments:

Post a Comment