#include <iostream> #include <vector> #include <algorithm> #include <stack> #include <string> #include <set> // vector<vector<int> > ans; // vector<int> tmp // set<vector<int> > ans; using namespace std; class Solution { public: int bestSol(vector<int>& values, int target){ if (values.empty()) return -1; if (values.empty()) return -1; if (target < 0) return -1; vector<int> ans(target+1,0); // 先从小到大考虑 钱的数量, 在从小到大考虑币种 // 在循环中完成更新, 如果当前的价值大于硬币的价值, 这个条件一定有, // 那就从当前价值中减掉硬币的价值,得到之前已经记录好的某一个值, // 然后把这枚硬币添加进去, 就是+1 for (int i = 1; i < target + 1; i++) { ans[i] = target / values[0]; for (int j = 0; j < values.size(); j++) { if (i >= values[j]){ ans[i] = min(ans[i], ans[i - values[j]] + 1); } } } for (int i = 0; i < target + 1; i++) { cout << "i : " << i << " least coin is " << ans[i] << endl; } return ans[target]; } }; int main() { vector<int> values{ 1, 3, 5 }; Solution s = Solution(); cout << s.bestSol(values, 11) << endl; system("pause"); return 0; }
硬币找零问题
猜你喜欢
转载自blog.csdn.net/weixin_36149892/article/details/80192117
今日推荐
周排行