c语言组合问题:10个数中选3个,输出所有可能情况

sonofthesea 2009-05-03 08:45:32
求各位给优化一下算法,个人觉得太。。。


#include<stdio.h>
static int b[3]={0,0,0};
static flag1[10]={1,1,1,1,1,1,1,1,1,1};
static flag2[1000][255];


static count;
int sort(int a[5],int depth );
void main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};

int p=0,q=0;
sort(a,0);
for(int i=0;i<count;i++)
{
{
for(int j=0;j<255;j++)
if(flag2[i][j]==1) {printf("%d ",j);}
}

printf("\n");
}



}



int sort(int a[10],int depth )
{
int i;
if(depth==3)
{
for(int f=0,int t=0;f<count;f++)
if(flag2[f][b[0]]==1&&flag2[f][b[1]]==1&&flag2[f][b[2]]==1)
{t++;}
if(t==0)
{flag2[count][b[0]]=1;flag2[count][b[1]]=1;flag2[count][b[2]]=1; count++;}
depth--;
return 1;
}
else
for(i=0;i<10;i++)
{
if(flag1[i]==1)
{
b[depth]=a[i];
flag1[i]=0;
depth++;
sort(a,depth);
depth--;
flag1[i]=1;
}
}
}

...全文
849 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
sean_zhou 2009-05-03
  • 打赏
  • 举报
回复
要通用性的话 用一个n位的二进制数,求里面1的个数是m个就可以了,不过这个算法时间复杂度是n*2^n,当n大时算的很慢,不知道有啥好办法。
sonofthesea 2009-05-03
  • 打赏
  • 举报
回复
这个是前几天一个人问的,我想了老半天,
只是勉强写出了代码,自觉地效率很低
你说的三重循环的话,没有通用性啊。
可以贴出来瞧瞧
sean_zhou 2009-05-03
  • 打赏
  • 举报
回复
这个问题我找到的最好算法就是遍历,一个一个比,三次for循环。

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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