c语言字符全排列数组,C语言用回溯算法实现求字符串的全排列

算法一:

#include

#include

#include

#define N 10

struct    FOOTPRINT

{

char cord[N];

};

void StrCopy(char *a,char *b);

int Match(char *p,struct FOOTPRINT *a);

void Show(struct RESULT *result);

void Delete(char *p,char a);

void Add(char a,struct FOOTPRINT *p);

int iCount=1;

int main()

{

clock_t start,finish;

start=clock();

char *seek;

char *head;

char *mhou;

int i,j,n;

struct FOOTPRINT  *cur;

printf("输入字符串(不超过10个):\n");

head=(char*)malloc(sizeof(char));

mhou=(char*)malloc(sizeof(char));

gets(head);

printf("全排列:\n");

i=0;

while(*(head+i)!='\0')

i++;

n=i;

cur=(struct FOOTPRINT* )malloc(n*sizeof(struct FOOTPRINT));

i=0;

while(*(head+i)!='\0')

{

(cur+i)->cord[0]=*(head+i);

(cur+i)->cord[1]='\0';

i++;

}

printf("%s\t",head);

seek=head+n-1;

while(1)

{

StrCopy(seek,mhou);

i=0;

while(*(mhou+i)!='\0')

{

*seek=*(mhou+i);

if(!Match(seek,cur+(seek-head)))

{

Add(*seek,cur+(seek-head));

for(j=seek-head+1;j

{

cur[j].cord[0]='\0';

}

Delete(mhou,*seek);

seek++;

while(seek<=head+n-1)

{

*seek=*mhou;

Delete(mhou,*mhou);

Add(*seek,cur+(seek-head));

seek++;

}

iCount++;

printf("%s\t",head);

if(iCount%5==0)

printf("\n");

seek=head+n-1;

break;

}

i++;

}

if(seek!=head+n-1)

*seek=*mhou;

if(seek==head)

break;

seek--;

}

finish=clock();

free(cur);

printf("\niCount=%d\n",iCount);

printf("use time:%f  ",(double)(finish-start)/CLOCKS_PER_SEC);

return 0;

}

void StrCopy(char *a,char *b)

{

int i=0;

while(*(a+i)!='\0')

{

*(b+i)=*(a+i);

i++;

}

*(b+i)='\0';

}

int Match(char *p,struct FOOTPRINT *a)

{

int i=0;

while(a->cord[i]!='\0')

{

if(*p==a->cord[i])

return 1;

i++;

}

return 0;

}

void Delete(char *p,char a)

{

int i=0;

while(*(p+i)!=a)

i++;

while(*(p+i+1)!='\0')

{

*(p+i)=*(p+i+1);

i++;

}

*(p+i)='\0';

}

void Add(char a,struct FOOTPRINT *p)

{

int i=0;

while(p->cord[i]!='\0')

i++;

p->cord[i+1]='\0';

while(i>0)

{

p->cord[i]=p->cord[i-1];

i--;

}

p->cord[0]=a;

}

算法二:

#include

#include

#define N 5

int count=0;

void show(char a[]);

void swap(char *a,char *b);

void permgen(char a[],int n);

void show(char a[])

{

int i;

for(i=0;i

{

printf("%c,",a[i]);

}

printf("\n");

count=count+1;

}

void swap(char *a,char *b)

{

char temp;

temp=*a;

*a=*b;

*b=temp;

}

void permgen(char a[],int n)

{

if(n<=1)

{show(a);return;}

int i;

for(i=0;i

{

swap(a+i,a+n-1);

permgen(a,n-1);

swap(a+i,a+n-1);

}

}

int main()

{

clock_t finish;

printf("hello world!\n");

char a[N]={'a','b','c','d','e'};

permgen(a,N);

printf("The count =%d\n",count);

finish=clock();

printf("use time:%f",(double)finish/CLOCKS_PER_SEC);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值