-
Notifications
You must be signed in to change notification settings - Fork 0
/
coin_change.cpp
91 lines (76 loc) · 2.22 KB
/
coin_change.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// https://leetcode.com/problems/coin-change/
// May 18, 2016
#include <iostream>
#include <vector>
#include <limits>
#include <queue>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount)
{
initialize_vectors(amount);
int startVertex = 0;
int targetVertex = amount;
queue<int> Q;
vecMinChange_[startVertex] = 0;
vecMinChange_[startVertex] = 0;
Q.push(startVertex);
vecVisited_[startVertex] = true;
while (!Q.empty())
{
int curVertex = Q.front();
Q.pop();
for (vector<int>::iterator it = coins.begin(); it != coins.end(); ++it)
{
int coin = *it;
int nextVertex = curVertex + coin;
if (nextVertex > targetVertex)
{
continue;
}
if (vecVisited_[nextVertex])
{
continue; // already visited
}
vecMinChange_[nextVertex] = 1 + vecMinChange_[curVertex];
vecVisited_[nextVertex] = true;
Q.push(nextVertex);
}
}
if (vecVisited_[targetVertex])
{
return vecMinChange_[targetVertex];
}
else
{
return -1;
}
}
private:
void initialize_vectors(int amount)
{
vecMinChange_.reserve(amount+1);
vecVisited_.reserve(amount+1);
for (unsigned int i=0; i != (amount+1); ++i)
{
vecMinChange_.push_back(numeric_limits<int>::max());
vecVisited_.push_back(false);
}
}
private:
// Following vectors will have index: [0,1,...,amount]
vector<int> vecMinChange_; // Stores the number of coin change for achieve total=index(of the vector)
vector<bool> vecVisited_;
};
int main(int argc, char* argv[])
{
Solution sln;
vector<int> coins = {2};
int amount = 3;
int minCoinChange = sln.coinChange(coins, amount);
cout << "Fewest number of coins to up the amount: " << minCoinChange << endl;
return 0;
}
/* Solved using shortest paths. This problem can also be solved using dynamic programming.
*/