递归的方法实现全排列,哪里出有关问题了
递归的方法实现全排列,哪里出问题了
[code=C/C++][/code]
#include<stdio.h>
void swap(char& a,char& b)
{
char temp;
temp=a;
a=b;
b=temp;
}
void perm(char a[],int start,int end)
{
int i;
if(start==end)
{
for(i=0;i<=end;i++)
printf("%c ",a[i]);
printf("\n");
}
else
{
for(i=start;i<=end;i++)
{
swap(a[start],a[end]);
perm(a,start+1,end);
swap(a[start],a[end]);
}
}
}
int main()
{
char a[5]={'a','b','c','d','e'};
perm(a,0,4);
return 1;
}
楼主感觉没错啊,但运行时结果不对,求大神
------解决方案--------------------
改成以下这样之后,无语法错误,可以运行,但是输出几乎一模一样,逻辑可能错了,不知原题是什么?
[code=C/C++][/code]
#include<stdio.h>
void swap(char& a,char& b)
{
char temp;
temp=a;
a=b;
b=temp;
}
void perm(char a[],int start,int end)
{
int i;
if(start==end)
{
for(i=0;i<=end;i++)
printf("%c ",a[i]);
printf("\n");
}
else
{
for(i=start;i<=end;i++)
{
swap(a[start],a[end]);
perm(a,start+1,end);
swap(a[start],a[end]);
}
}
}
int main()
{
char a[5]={'a','b','c','d','e'};
perm(a,0,4);
return 1;
}
楼主感觉没错啊,但运行时结果不对,求大神
------解决方案--------------------
改成以下这样之后,无语法错误,可以运行,但是输出几乎一模一样,逻辑可能错了,不知原题是什么?
- C/C++ code
#include<stdio.h> void swap(char *a,char *b) { char temp; temp=*a; *a=*b; *b=temp; } void perm(char a[],int start,int end) { int i; if(start==end) { for(i=0; i<=end; i++) printf("%c ",a[i]); printf("\n"); } else { for(i=start; i<=end; i++) { swap(&a[start],&a[end]); perm(a,start+1,end); swap(&a[start],&a[end]); } } } int main() { char a[5]= {'a','b','c','d','e'}; perm(a,0,4); return 1; }
------解决方案--------------------
- C/C++ code
void swap(char * a,char * b) { char temp; temp=*a; *a=*b; *b=temp; } void perm(char a[],int start,int end) { int i; if(start==end) { for(i=0;i<=end;i++) printf("%c ",a[i]); printf("\n"); } else { for(i=start;i<=end;i++) { swap(&a[start],&a[i]); perm(a,start+1,end); swap(&a[start],&a[i]); } } }
------解决方案--------------------
- C/C++ code
#include<stdio.h> #include <memory.h> int nTotal =0; 递归调用那里有问题,由于数组a是会被改变的,因此最后时候的swap可能不是想要的 简单改了一下: void swap(char& a,char& b) { char temp; temp=a; a=b; b=temp; } void perm(char a[],int start,int end) { int i; if(start==end) { for(i=0;i<=end;i++) printf("%c ",a[i]); printf("\n"); nTotal++; } else { char tmpBuf[100]; memcpy(tmpBuf,a+start,end-start+1); for(i=start;i<=end;i++) { perm(a,start+1,end); memcpy(a+start,tmpBuf,end-start+1); swap(a[start],a[i+1]); } } } int main() { char a[5]={'a','b','c','d','e'}; perm(a,0,4); printf("total=%d \n" ,nTotal); getchar(); return 1; }