TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
coin_change_topdown.cpp
Go to the documentation of this file.
1
21#include <cassert> // for assert
22#include <climits> // for INT_MAX
23#include <iostream> // for io operations
24#include <vector> // for std::vector
25
30namespace dynamic_programming {
36namespace mincoins_topdown {
46template <typename T>
47int64_t mincoins(const T &n, const std::vector<T> &coins, const int16_t &t,
48 std::vector<T> dp) {
49 if (n == 0) {
50 return 0;
51 }
52 if (dp[n] != 0) {
53 return dp[n];
54 }
55 int ans = INT_MAX; // variable to store min coins
56 for (int i = 0; i < t; i++) {
57 if (n - coins[i] >= 0) { // if after subtracting the current
58 // denomination is it greater than 0 or not
59 int sub = mincoins(n - coins[i], coins, t, dp);
60 ans = std::min(ans, sub + 1);
61 }
62 }
63 dp[n] = ans;
64 return dp[n]; // returns minimum number of coins
65}
66
67} // namespace mincoins_topdown
68} // namespace dynamic_programming
69
74static void test() {
75 // example 1: number of coins=3 and minimum coins required=3(7,7,1)
76 const int64_t n1 = 15;
77 const int8_t t1 = 3, a1 = 0;
78 std::cout << "\nTest 1...";
79 std::vector<int64_t> arr1{1, 7, 10};
80 std::vector<int64_t> dp1(n1 + 1);
81 fill(dp1.begin(), dp1.end(), a1);
82 assert(dynamic_programming::mincoins_topdown::mincoins(n1, arr1, t1, dp1) ==
83 3);
84 std::cout << "Passed\n";
85}
86
91int main() {
92 test(); // execute the test
93 return 0;
94}
static void test()
Test implementations.
int64_t mincoins(const T &n, const std::vector< T > &coins, const int16_t &t, std::vector< T > dp)
This implementation is for finding minimum number of coins .
int main()
Main function.
std::string fill(char c, int n)
for std::vector
Dynamic Programming algorithms.
Functions for minimum coin exchange problem.