问:如何用递归求解组合数?
给定M个元素,从中选出N个元素。如何用递归的方法将所有的组合情况输出。最好能有详尽 的代码和解释。万分感谢!!!! 期待大侠们的指导 诶~~这个用递归啊 我还真的不会 为什么一定要用递归呢??int n = 0;
void swap(char *a, char *b)
{
char m;
m = *a;
*a = *b;
*b = m;
}
void perm(char list[], int k, int m)
{
int i;
if(k > m)
{
for(i = 0; i <= m; i++)
printf("%c ", list);
printf("\n");
n++;
}
else
{
for(i = k; i <= m; i++)
{
swap(&list, &list);
perm(list, k + 1, m);
swap(&list, &list);
}
}
}
int main()
{
char list[] = {'a','b','c', 'd', 'e'};
perm(list, 0, 4);
printf("total:%d\n", n);
system("pause");
return 0;
}
戏++ 发表于 2014-7-23 09:13
这个貌似是求全排列吧? #include <stdio.h>
struct Number
{int id;
int num;
struct Number *next;
};
struct Number_1
{struct Number *x1;
struct Number_1 *x2;
};
void numpri(struct Number_1 *head_1)
{struct Number_1 *q1=head_1;
int f;
if(q1!=0)
{
do
{f=(*(*q1).x1).num;
printf("%8d ",f);
q1=(*q1).x2;
}while(q1!=0);
printf("\n");
}
}
void sub(struct Number_1 *head_1,struct Number_1 *p3,int m,int n)
{struct Number_1 *p4,*p5=p3,*p6;
int f;
if(head_1==0){p4=p3;}
else{p4=head_1;}
for(f=m;f>=n;f--)
{
if(n>1)
{p5=(struct Number_1 *)malloc(sizeof(struct Number_1));
(*p5).x1=(*(*p3).x1).next;
(*p5).x2=0;
(*p3).x2=p5;
sub(p4,p5,f-1,n-1);
(*p3).x1=(*(*p3).x1).next;
}
else
{
while((*p5).x1!=0)
{numpri(p4);
(*p5).x1=(*(*p5).x1).next;
}
break;
}
}
}
void main()
{int m,n;
int i;
struct Number *head,*p1,*p2;
head=0;
p1=(struct Number *)malloc(sizeof(struct Number));
printf("请输入总元素个数M:\n");
scanf("%d",&m);
if(m>0)
{
head=p1;
for(i=0;i<m;i++)
{
p2=p1;
(*p2).id=i;
printf("请输入第%d个元素值:",i);
scanf("%d",&(*p2).num);
p1=(struct Number *)malloc(sizeof(struct Number));
(*p2).next=p1;
}
(*p2).next=0;
printf("输入完毕,请再输入需要从中取出的元素个数:");
scanf("%d",&n);
if(n<=m&&n>0)
{
struct Number_1 *p3,*head_1=0;
p3=(struct Number_1 *)malloc(sizeof(struct Number_1));
(*p3).x1=head;
(*p3).x2=0;
sub(head_1,p3,m,n);
}
else
{printf("N值无意义!\n");}
}
else
{printf("M值无意义!\n");}
}
页:
[1]