[英]Coin Change DP Algorithm Print All Combinations
經典硬幣找零問題在這里得到了很好的描述: http : //www.algorithmist.com/index.php/Coin_Change
在這里,我不僅想知道有多少種組合,而且還要打印出所有組合。 我在實現中的鏈接中使用了相同的DP算法,但沒有在DP表中記錄DP[i][j] = count
的組合,而是將組合存儲在表中。 因此,我為此DP表使用了3D向量。
我嘗試改進我的實現,注意到在查找表時,僅需要最后一行的信息,因此我並不需要總是存儲整個表。
但是,改進后的DP解決方案似乎仍然很慢,因此我想知道下面的實現中是否存在問題,或者是否可以進行更多優化。 謝謝!
您可以直接運行代碼:
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
int total = 10; //total amount
//available coin values, always include 0 coin value
vector<int> values = {0, 5, 2, 1};
sort(values.begin(), values.end()); //I want smaller coins used first in the result
vector<vector<vector<int>>> empty(total+1); //just for clearing purpose
vector<vector<vector<int>>> lastRow(total+1);
vector<vector<vector<int>>> curRow(total+1);
for(int i=0; i<values.size(); i++) {
for(int curSum=0; curSum<=total; curSum++){
if(curSum==0) {
//there's one combination using no coins
curRow[curSum].push_back(vector<int> {});
}else if(i==0) {
//zero combination because can't use coin with value zero
}else if(values[i]>curSum){
//can't use current coin cause it's too big,
//so total combination for current sum is the same without using it
curRow[curSum] = lastRow[curSum];
}else{
//not using current coin
curRow[curSum] = lastRow[curSum];
vector<vector<int>> useCurCoin = curRow[curSum-values[i]];
//using current coin
for(int k=0; k<useCurCoin.size(); k++){
useCurCoin[k].push_back(values[i]);
curRow[curSum].push_back(useCurCoin[k]);
}
}
}
lastRow = curRow;
curRow = empty;
}
cout<<"Total number of combinations: "<<lastRow.back().size()<<endl;
for (int i=0; i<lastRow.back().size(); i++) {
for (int j=0; j<lastRow.back()[i].size(); j++) {
if(j!=0)
cout<<" ";
cout<<lastRow.back()[i][j];
}
cout<<endl;
}
return 0;
}
看來你復制過多的載體:至少在過去的else
可改寫為
// not using current coin
curRow[curSum] = lastRow[curSum];
const vector<vector<int>>& useCurCoin = curRow[curSum - values[i]]; // one less copy here
// using current coin
for(int k = 0; k != useCurCoin.size(); k++){
curRow[curSum].push_back(useCurCoin[k]);
curRow[curSum].back().push_back(values[i]); // one less copy here too.
}
即使可讀curRow = empty;
,這可能會導致分配。 更好地創建函數
void Clean(vector<vector<vector<int>>>& vecs)
{
for (auto& v : vecs) {
v.clear();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.