fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4. using namespace std;
  5.  
  6. // create a map to store solutions of subproblems
  7. unordered_map<string, int> lookup;
  8.  
  9. // Function to find the total number of distinct ways to get change of N
  10. // from unlimited supply of coins in set S
  11. int count(int S[], int n, int N)
  12. {
  13. // if total is 0, return 1 (solution found)
  14. if (N == 0)
  15. return 1;
  16.  
  17. // return 0 (solution do not exist) if total become negative or
  18. // no elements are left
  19. if (N < 0 || n < 0)
  20. return 0;
  21.  
  22. // construct an unique map key from dynamic elements of the input
  23. string key = to_string(n) + "|" + to_string(N);
  24.  
  25. // if sub-problem is seen for the first time, solve it and
  26. // store its result in a map
  27. if (lookup.find(key) == lookup.end())
  28. {
  29. // Case 1. include current coin S[n] in solution and recur
  30. // with remaining change (N - S[n]) with same number of coins
  31. int include = count(S, n, N - S[n]);
  32.  
  33. // Case 2. exclude current coin S[n] from solution and recur
  34. // for remaining coins (n - 1)
  35. int exclude = count(S, n - 1, N);
  36.  
  37. // assign total ways by including or excluding current coin
  38. lookup[key] = include + exclude;
  39. }
  40.  
  41. // return solution to current sub-problem
  42. return lookup[key];
  43. }
  44.  
  45. // Coin Change Problem
  46. int main()
  47. {
  48. // n coins of given denominations
  49. int S[] = { 2, 3, 5};
  50. int n = sizeof(S) / sizeof(S[0]);
  51.  
  52. // Total Change required
  53. int N = 9;
  54.  
  55. cout << "Total number of ways to get desired change is "
  56. << count(S, n - 1, N);
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 4844KB
stdin
Standard input is empty
stdout
Total number of ways to get desired change is 3