简单问题!!!如何求组合数列

zhao_as 2003-07-17 06:20:36
比如有1.2.3 3个数字
求2个组合起来的数列
答案是
1,2
1,3
2,3
但是求1...10个数字
3个或者更多数的组合呢?不要求个数,那个谁都会
有没有好的算法?
解决立刻给分


...全文
168 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
bigtea 2003-07-18
  • 打赏
  • 举报
回复
楼上两位,人家是问组合的枚举。
zhao_as 2003-07-18
  • 打赏
  • 举报
回复
谢谢cdocument(文档)
接分!
buaaaladdin 2003-07-17
  • 打赏
  • 举报
回复
楼上的全排列也可以用STL\algorithm\next_permutation(),没有用递归,算法也很巧妙,具体实现可以看侯捷的STL源码分析。
njuhuangmy 2003-07-17
  • 打赏
  • 举报
回复
使用了 递归 算法, 全排列。
字符 , 数字 处理是一样的
来自 网络 , 值得一提的是,这个 对 11234 , 这样的数列
也能正确进行全部 排列 :)

个人对这个程序 极其 喜爱,尤其是对 最后的 sort 函数
细想之下,发现可以对这个 sort 最很多改进,或者 因为
有 sort , 而可以添加很多功能

#define N 21
#include <stdio.h>
#include <string.h>
#include <ctype.h>

char d[N];

int length;

void Permutation(char s[], int i);
void Sort(char s[]);

int count = 0;
void main()
{
char s[N],ss[N];
int flag ;
do
{
printf("Please input less than 20 characters. \n");
gets(s);
flag = 0;
strcpy(ss,"\0");
int ilength = strlen(s);
if (ilength < 5)
flag = 1;
for (int icount = 0; icount < 5; icount++)
{
if(!isalpha(s[icount]))
flag = 1;
}
strcpy(ss,s);
}
while (flag == 1);

//Sort(ss);
printf("How many characters do you want to permute: \n");
printf("Enter a number : ");
scanf("%d", &length);

printf("You input : %s\n",ss);

Sort(ss);
Permutation(ss, 0);
}

void Permutation(char s[], int i)
{
int j;
char temp;
for(j = 0; j < length; j ++)
if(s[j] == s[j - 1])
;
else if(s[j] != '#')
{
d[i] = s[j];
temp = s[j];
s[j] = '#';
if(i == length - 1)
{
d[length] = '\0';
printf(" %10d : ", ++ count);
puts(d);
}
else
Permutation(s, i + 1);
s[j] = temp;
}
}

void Sort(char s[])
{
int i, j;
char temp;
for(i = 0; i < length - 1; i ++)
for(j = i + 1; j < length; j ++)
if(s[i] > s[j])
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
zteliubin 2003-07-17
  • 打赏
  • 举报
回复
up,
知道组合就知道该怎么做了吧!几次循环而已!
cdocument 2003-07-17
  • 打赏
  • 举报
回复
//有个对char型的,你改改吧。
#include <iostream>
using namespace std;

void print(char **p,int n)
{
char **t=p+n-1;
while(n--)
{
putchar(**t);
*t--;
}
putchar('\n');
}
int cmn(char *data ,int m,int n)
{
char **p;
int i;
p=new char* [n];//申请n个指向的指针
for(i=0;i<m;i++)
p[m-i-1]=data+i;//指向从开头的各个元素。
i=0;
for(;;)
{
print(p,m);
p[0]++;//移动最后一个指针,
if(*(p[0])=='\0')//到了末尾
{
i=1;
for(;;)//就把倒数第二个指针后移一个。
{
p[i]++;
if(*(p[i]+i)=='\0')
{
i++;
if(i==m)
goto exit;
}
else
break;
}
while(i>0)
{
p[i-1]=p[i]+1;
i--;
}
}
}
exit:
delete [] p;//释放
return 0;
}
int main()
{
char p[100];
int m,n;
cout<<"Input a string:"<<endl;
cin>>p;
cout<<"input M:";
cin>>m;
n=strlen(p);
if(m>n)
{
cout<<"Error number!"<<endl;
return 0;
}

cmn(p,m,n);
return 0;
}
//运行结果:
Input a string:
12345
input M:3
123
124
125
134
135
145
234
235
245
345

69,336

社区成员

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

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