题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2069
Coin Change
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23514 Accepted Submission(s): 8250
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.
26
13
#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<ctype.h>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9;
const int maxn=+;
const int maxm=;
const int maxx=1e4+;
const ll maxe=+;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int ans=;
for(int i=;i*<=n;i++)
{
for(int j=;j*<=n;j++)
{
for(int k=;k*<=n;k++)
{
for(int l=;l*<=n;l++)
{
for(int m=;m<=n;m++)
{
if(i*+j*+k*+l*+m==n&&i+j+k+l+m<=)
ans++;
}
}
}
}
}
cout<<ans<<endl;
}
return ;
}
思路2:dp思想,dp[i][j]表示使得价值为i,用了 j 个硬币。 可以把硬币的价值用a[]存起来,dp[i][j]=dp[i][j]+dp[i-a[k]][j-1]
具体看代码:
#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<ctype.h>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9;
const int maxn=+;
const int maxm=;
const int maxx=1e4+;
const ll maxe=+;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
int a[]={,,,,};
int dp[maxn][];//dp[i][j]表示使得价值为i,用了j个硬币的种数
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(dp,,sizeof(dp));//初始化都为0
int ans=;
dp[][]=;
for(int i=;i<;i++)//5种价值的硬币
{
for(int j=;j<=;j++)//个数
{
for(int k=a[i];k<=n;k++)//最小为当前的a[i],一直遍历到n
{
dp[k][j]+=dp[k-a[i]][j-];//从上一个加上使用这一个的情况
}
}
}
for(int i=;i<=;i++) ans+=dp[n][i];
cout<<ans<<endl;
}
return ;
}