0

古典的なコインの変更の問題は、ここでよく説明されています: 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;
}
4

1 に答える 1