The change-making problem, also known as minimum coin change problem, addresses the question of finding the minimum number of coins (of certain denominations) that add up to a given amount of money.
The Idea: The central idea is to build a tree BFS style. The root is initially the amount of change, and the child of every node is defined as parent - denomination. Since our goal is not only to return the minimum amount of coins possible, but which coins these are, our structure is also going to carry parent nodes from so we backtrack from earlier nodes. I also sorted the denominations in acending order. That way, when the moment a denomination fails to fit the current amount of the change, I know I can ignore the remaining denominations.
Complexity: ?
structCoin_Node {Coin_Node(constint r):remainder(r),parent(nullptr) {}Coin_Node(constint r,Coin_Node*p) :remainder(r),parent(p) {}constint remainder; Coin_Node *parent; vector<Coin_Node*> children;};vector<int> reach_root_get_coins(Coin_Node* bottom) { Coin_Node *iter = bottom;if (!iter) return {}; vector<int> change;int prev =iter->remainder; iter =iter->parent;while (iter) {int cur =iter->remainder;change.push_back(cur - prev); prev = cur; iter =iter->parent; }return change;}// this algorithm assumes that it is possible// to return the requested change with the denominatins// e.g. change can be completely factored by denominationsvector<int> min_coins_dp(vector<int> &denom,int change) {if (denom.empty() || change ==0) return {};sort(denom.begin(),denom.end()); queue<Coin_Node*> q; Coin_Node *root =newCoin_Node(change);q.push(root);while (!q.empty()) { Coin_Node *parent =q.front();q.pop();if (parent->remainder ==0) returnreach_root_get_coins(parent);for (int type : denom) {int remainder =parent->remainder - type;if (remainder >=0) { Coin_Node *next =newCoin_Node(remainder, parent);parent->children.push_back(next);q.push(next); }elsebreak; } }}