请问一个问题,数字的组合问题

leoh2000 2005-03-25 04:18:47
就是那个50美分,25美分,10美分,5美分,1美分的问题,任意输入一个数字,由以上的美分组成,共有多少种组合方法,列出每种组合。不知道我说清楚了没有?我现在能想到的就是用for循环来挨个循环,不过写出来可能是错的。不知道这个问题应该怎么去想呢?提出想法就可以了~代码我可以自己写,谢谢
...全文
126 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
冥王之锤 2005-03-25
  • 打赏
  • 举报
回复
pcboyxhy(-273.15℃)很厉害阿,上次那个打枪的问题,也是这么解决的。
tfq 2005-03-25
  • 打赏
  • 举报
回复
撇开效率不谈,用5个for循环看看:
#include <iostream>
#include <iomanip>
using namespace std;
void compute(int value);
int main()
{
int value;
cout<<"input the value:";
cin>>value;
compute(value);
return 0;
}

void compute(int value)
{
int m1,m2,m3,m4,m5; //m1,m2,m3,m4,m5为最大可能取值
int i,j,k,m,n;
int tmp=0,count=0;
m1=value/50;
m2=value/25;
m3=value/10;
m4=value/5;
m5=value/1;
cout<<" 50 25 10 5 1"<<endl;
cout<<"------------------------------------------------"<<endl;
for (i=0;i<=m1;i++)
for (j=0;j<=m2;j++)
for (k=0;k<=m3;k++)
for (m=0;m<=m4;m++)
for (n=0;n<=m5;n++)
{
tmp=50*i+25*j+10*k+5*m+1*n;

if (tmp==value)
{
count++;
cout<<setiosflags(ios::left);
cout<<"count "<<count<<":";
cout<<setw(8)<<i<<setw(8)<<j<<setw(8)<<k<<setw(8)<<m<<setw(8)<<n;
cout<<endl;
}
}
cout<<"所有的可能组合 "<<count<<endl;
}
nodummy 2005-03-25
  • 打赏
  • 举报
回复
逐个尝试实在是没有什么效率……

这种东西一般是靠贪心来解决的,对于目前给出的这组数据还可以用某些组合来进行简化……
inlin 2005-03-25
  • 打赏
  • 举报
回复
晚上回来帮你解决!
pcboyxhy 2005-03-25
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdlib>

using namespace std;

const int vsize = 5;
int value[vsize]={50, 25, 10, 5, 1};
int number[vsize]={0};
int total=1;

void out(int end)
{
cout<<endl<<"No. "<<total++<<" ";
for(int i=0; i<end; ++i)
if(number[i])
cout<<value[i]<<"分"<<number[i]<<"张 ";
}

void make(int val, int start)
{
if(val==0){out(start); return;}
if(val<0) return;
if(start>=5) return;
int maxs = val/value[start];
for(int i=0; i<=maxs; ++i)
{
number[start]=i;
make(val-i*value[start], start+1);
}
}


int main(int argc, char *argv[])
{
int v;
cin>>v;
make(v, 0);
system("PAUSE");
return 0;
}
leoh2000 2005-03-25
  • 打赏
  • 举报
回复
谢谢楼上的,现在正在往10,5,1的组合写,明后天不能上网了,回家继续写。下周来结帖子~谢谢大家,分不够可以再给~
pcboyxhy 2005-03-25
  • 打赏
  • 举报
回复
今晚有课
晚上回来帮你看
leoh2000 2005-03-25
  • 打赏
  • 举报
回复
先写了一个5,1组合的,大家看看对不对~谢谢大家,散分

#include <iostream>
using namespace std;
int main()
{
int num;
int na = 0;
int nb = 0;
int nc = 0;
int nd = 0;
int ne = 0;
int tmp = 0;
cout << "input the number :";
cin >>num;

while (nb <= num/5)
{
while (na <= num/1)
{
tmp = na*1+nb*5;

if (tmp == num)
{
cout << na<<endl;
na = 0;
break;

}
++na;
}
if (tmp == num)
{
cout <<nb<<endl;
}
++nb;
}
}
leoh2000 2005-03-25
  • 打赏
  • 举报
回复
自己顶一下

64,662

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧