一、題目
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
Inputcopy Outputcopy
11
26
4
13
二、分析
題意要求使用五種面值的硬幣,組成不同金額能有多少組合的方法
題目中有一個條件,硬幣的數量不能超過100。
那么下面這種遞推的方法就不能夠控制硬幣是數量
//錯誤代碼
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=1e3+5;
int dp[maxn];
int a[5]={1,5,10,25,50};
int main()
{int n;while(cin>>n){memset(dp,0,sizeof(dp));dp[0]=1;for(int i=0;i<5;i++)for(int j=a[i];j<=n;j++){dp[j]=dp[j]+dp[j-a[i]];}cout<<dp[n]<<endl;}
}
定義dp[i][j]表示i枚硬幣組成j有的方法總數
這樣就可以控制硬幣的數量
//正確代碼
#include <iostream>
#include <cstring>
using namespace std;
int dp[110][260];
// dp[i][j]表示i枚硬幣組成j有的方法總數
int a[6] = {1, 5, 10, 25, 50};
int main()
{int n;while (cin >> n){memset(dp, 0, sizeof(dp));dp[0][0] = 1;for (int i = 0; i < 5; i++)for (int j = a[i]; j <= n; j++)for (int k = 1; k <= 100; k++){dp[k][j] += dp[k - 1][j - a[i]];}int ans = 0;for (int i = 0 ;i<= 100; i++)//要從0開始{ans += dp[i][n];}cout << ans << endl;}
}