Coin Change

一、题目

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
#include
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 
#include 
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;
    }
}

你可能感兴趣的:(算法,c++,数据结构,c语言)