Coin Change
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17261 Accepted Submission(s): 5905
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.
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
Sample Output
4 13
Author
Lily
Source
Recommend
linle
他要求硬币总数不超过100
这时候我们就要增加一个维度来限制数量,dp[i][j]表示用不超过i个硬币组成j的总数
最外一层枚举硬币总类和上面一样的道理,dp[num][j] += dp[num - 1][j - c[i]]这里是对于新来的每一个硬币,= 放这个硬币的总数+不放这个硬币的总数,
d[num-1][j-c[i]]是之前已经更新到有k-1个新硬币的了,而这个式子只针对地k个新硬币所以num-1是未放这个新硬币之前的答案,即dp[j - c[i]]放的都只是放一个硬币
(第k个新硬币)得到的总数
然后答案要累加不超过i:0-->100得到的总数,一定要从0开始累加,因为数据有0个硬币的总数
这时候我们就要增加一个维度来限制数量,dp[i][j]表示用不超过i个硬币组成j的总数
最外一层枚举硬币总类和上面一样的道理,dp[num][j] += dp[num - 1][j - c[i]]这里是对于新来的每一个硬币,= 放这个硬币的总数+不放这个硬币的总数,
d[num-1][j-c[i]]是之前已经更新到有k-1个新硬币的了,而这个式子只针对地k个新硬币所以num-1是未放这个新硬币之前的答案,即dp[j - c[i]]放的都只是放一个硬币
(第k个新硬币)得到的总数
然后答案要累加不超过i:0-->100得到的总数,一定要从0开始累加,因为数据有0个硬币的总数
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int dp[500][500];
int main()
{
int n,m,i,k,j,h,sum;
int c[]={0,1,5,10,25,50};
while(cin>>h)
{
memset(dp,0,sizeof(dp));
dp[0][0]=1;
for(i=1;i<=5;i++)
{
for(k=1;k<=100;k++)//因为不能超过100枚 所以需要二维数组
{
for(j=c[i];j<=h;j++)
{
dp[k][j]+=dp[k-1][j-c[i]];
}
}
}
sum=0;
for(i=0;i<=100;i++)
{
sum+=dp[i][h];
}
cout<<sum<<endl;
}
return 0;
}
本文介绍了一个经典的动态规划问题——硬币找零问题,旨在找出构成特定金额的不同组合方式总数。考虑到硬币总数上限为100,通过三维数组进行状态转移,实现了高效的求解。
445

被折叠的 条评论
为什么被折叠?



