题目:生成6取4的排列,先生成组合,然后把组合生成排列,组合按字典序
程序好像不是字典序的
有空再改
#include<stdio.h>
int visited[20];
int workarr[20];
int elem[20]={0};
int b[30]={0};
int counter=0;
FILE *fp;
void DFS(int l,int n)//l为深搜的位,n为元素的个数
{
int i;
if (l == n)
{
for (i=0; i<l; i++)
fprintf(fp,"%d ", workarr[i]);
fprintf(fp," ");
counter++;
if(counter%6==0)
fprintf(fp,"/n");
return;
}
for (i=0; i<n; i++)
if (!visited[i])
{
visited[i] = 1;//确保不重复
workarr[l] = elem[i];
DFS(l+1,n);
visited[i] = 0;
}
}
int dtb(int d)//convert dec to binary
{
int i=1;
while(d>0)
{
b[i++]=d%2;
d/=2;
}
return i-1;//长度,从1开始
}
void bts(int n)//convert binary to screen
{
int i;
int j;
for(i=1,j=0;i<=n;i++)
{
if(b[i]==1)
{
elem[j++]=i;
}
}
for(i=0;i<=8;i++)
visited[i]=0;
DFS(0,j);
fprintf(fp,"/n");
}
int xtwoy(int n)//power(2,n)
{
if (n==0)
return 1;
return 2*xtwoy(n-1);
}
int right(int m,int n)//determine if the binary is just the number asked
{
int i;
int count=0;
for(i=1;i<=n;i++)
{
if(b[i]==1) count++;
}
return (count==m)?1:0;
}
main()
{
int i;
int wei;
if((fp=fopen("out.txt","w"))==NULL)
{
printf("error");
exit(0);
}
for(i=0;i<xtwoy(6);i++)
{
wei=dtb(i);
if(right(4,wei))
{
bts(wei);
}
}
fprintf(fp,"%d",counter);
}