
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Coin Change Problem II 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]]
- for j in range coins[i] to amount
- return dp[amount]
Example(C++)
Let us see the following implementation to get better understanding −
#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
Advertisements