# 硬币问题

（以后在更新吧）

### 3. 代码

``````//
// Created by Administrator on 2021/7/20.
//

#ifndef C__TEST01_COINDP_HPP
#define C__TEST01_COINDP_HPP

#include "iostream"
#include <vector>
using namespace std;

class CoinDP {
public:
CoinDP(vector<int> An, int M);
vector<int> algorithmDP(vector<int> &A, int &M);
private:
int M;
vector<int> A;
};

CoinDP::CoinDP(vector<int> An, int M):
A(An),M(M)
{
A.resize(An.size());
}

vector<int> CoinDP::algorithmDP(vector<int> &A, int &M){
vector<int> f;
f.resize(M+1);
int i = 0;
int j = 0;
f[0] = 0; //Initialization

for(i = 1; i < f.size(); ++i){
f[i] = INT_MAX;
// the types of coins
for (j = 0; j < A.size(); ++j) {
//1. money is positive
//2. if f[i-A[j]] is INT_MAX, f[i] must be INT_MAX
//3. i-A[j] = i - 2, i - 5, i - 7
if(i-A[j] >= 0 && f[i-A[j]] != INT_MAX){
f[i] = min(f[i], f[i-A[j]] + 1);
}
}
}
if(f[M] == INT_MAX){
f[M] = -1;
}
return f;
}
#endif //C__TEST01_COINDP_HPP

``````

``````#include <iostream>
using namespace std;
#include "CoinDP.hpp"
//动态规划问题：2元，5元，7元硬币，凑成27元

int main() {
vector<int> An = {2,5,7};
int M = 27;
CoinDP cdp(An, M);

vector<int> f;
f = cdp.algorithmDP(An, M);

for(vector<int>::iterator it = f.begin(); it!=f.end();it++){
cout << *it << " ";
}
return 0;
}
``````

(0)
(0)