举个例子,比如1,2,3,4这4个数,从中选出任意不同的三个数有几种方案。一共有4种,123,124,134,234;这个就是排列组合算法,现在看看具体算法怎么实现;
假设n个数,从中选择k个不同的数,首先我想到的就是可以充当4个链表,每个链表的数据都是n个数,依次进行访问,确保下一个链表的指针要比前一个链表的指针大,这样才能实现不同,后来发现这样效率很低,于是采用了数组去维护链表指针,可以看做是k个层,根据每层的值来确定指针位置;
代码如下:
#include <stdio.h>
#include <stdlib.h>
int alltest(int s[],int length,int t)
{
int temp[100]={0};
int k=0;
int i=0;
int layer=0;
int res[t];
int a=length-t;
int count=0;
while(temp[0]<=a)
{
while(layer<=t-2)
{
res[layer]=s[temp[layer]];
layer++;
temp[layer]=temp[layer-1]+1;
}
temp[layer]=temp[layer-1]+1;
while(temp[layer]<length)
{
res[layer]=s[temp[layer]];
for(i=0;i<t;i++)
{
printf("%d ",res[i]);
}
count++;
printf("\n");
temp[layer]++;
}
layer=t-1;
while(temp[layer]>=length)
{
// printf("temp=%d\n",temp[layer]);
temp[layer]=0;
layer--;
}
temp[layer]++;
res[layer]=s[temp[layer]];
// k=0;
}
printf("count=%d\n",count);
}
int main()
{
int array[8]={1,2,3,4,5,6,7,8};
alltest(array,8,8);
}