所有硬币组合问题——动态规划hdu2069

Posted sunjianzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了所有硬币组合问题——动态规划hdu2069相关的知识,希望对你有一定的参考价值。

Problem Description
Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.

For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, or two 5-cent coins and one 1-cent coin, or one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.

Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 100 coins.
 

 

Input
The input file contains any number of lines, each one consisting of a number ( ≤250 ) for the amount of money in cents.
 

 

Output
For each input line, output a line containing the number of different ways of making changes with the above 5 types of coins.
 

 

Sample Input
11 26
 
现附上AC代码:

#include<iostream>
using namespace std;
const int money=251;
const int coin=101;
int dp[money][coin]=0; //dp[i][j]表示金额为i,硬币数为j的种类方法
int value[5]=1,5,10,25,50;

void solve()

//for(int i=0;i<money;i++) 这里为什么只能dp[0][0]=0,是因为dp[j][1]=dp[j][1]+dp[j-value[i]][k-1],只有j-value[i]==0时,才能在加1
//dp[i][0]=1;
dp[0][0]=1;
for(int i=0;i<5;i++)

for(int j=value[i];j<money;j++)

for(int k=1;k<coin;k++)

dp[j][k]=dp[j][k]+dp[j-value[i]][k-1];




int main()

solve();
int ans[money]=0;
ans[0]=1; //注意这一步,一定不能忘,一个特殊值
for(int i=1;i<money;i++)

for(int j=1;j<coin;j++)

ans[i]=dp[i][j]+ans[i];


int s;
while(cin>>s)
cout<<ans[s]<<endl;
return 0;

 

因为刚开始学习动态规划,这种硬币问题算是入门的问题。到现在为止,我所理解的动态规划是利用递推关系式,对于某个解值是需要用之前的算出来的进行求解,也就是类似于我要想知道第三个值的数,就需要让第一个数乘以第二个数,举个例子,就像我们都熟知的斐波那契数列,但要注意初始值一定要弄明白,否则递推关系式将进行不下去。另外斐波那契数列是最简单的dp,稍微复杂一点的需要进行不止一次地递推,就像这次的硬币问题,需要递推5次。

以上是关于所有硬币组合问题——动态规划hdu2069的主要内容,如果未能解决你的问题,请参考以下文章

春招好题 | 动态规划——硬币问题及其变形

动态规划---爬楼梯和硬币组合问题

硬币问题-动态规划详解

基本动态规划之硬币问题

322.零钱兑换(动态规划)

算法学习:动态规划