Coin Change 2 in C++


Suppose we have coins of different denominations and a total amount of money. we have to Write a module to compute the number of combinations that make up that amount. we can assume that we have infinite number of each kind of coin. So if the amount is 5 and coins are [1, 2, 5], then there are four combinations. (1+1+1+1+1), (1+1+1+2), (1+2+2), (5)

To solve this, we will follow these steps −

  • create one array dp of size amount + 1
  • dp[0] := 1
  • n := size of coins array
  • for i in range 0 to n – 1
    • for j in range coins[i] to amount
      • dp[j] := dp[j – coins[i]]
  • return dp[amount]

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int change(int amount, vector<int>& coins) {
      vector <int> dp(amount + 1);
      dp[0] = 1;
      int n = coins.size();
      for(int i = 0; i < n; i++){
         for(int j = coins[i]; j <= amount; j++){
            dp[j] += dp[j - coins[i]];
         }
      }
      return dp[amount];
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,5};
   cout << (ob.change(5, v));
}

Input

5
[1,2,5]

Output

4

Updated on: 29-Apr-2020

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements