当前页面: 开发资料首页 → J2SE 专题 → 有关递归的一个费解的问题
有关递归的一个费解的问题
摘要: 有关递归的一个费解的问题
如何写出一个方法print(String s)使它能打印出s中所有字符的排列
如:
print("abc");
输出:
abc
acb
bac
bca
cab
cba
只要打印全排列还是要用递归打印呢
递归?
楼主是想用递归来实现全排列吧,下面是我上学时的一小段C代码,楼主可以参考一下...
#include
#include
void Perm(int P[],int m,int n);
void print(int P[],int n);
int main()
{
int j;
int n;
int *P;
scanf("%d",&n);
P=(int *)malloc((n+1)*sizeof(int));
for (j=1;j<=n;j++)
{
P[j]=j;
}
Perm(P,1,n);
system("pause");
}
//Functions
void Perm(int P[],int m,int n)
{
int j,tmp;
if (m==n)
print(P,n);
else
{
for (j=m;j<=n;j++)
{
tmp=P[j];
P[j]=P[m];
P[m]=tmp;
Perm(P,m+1,n);
tmp=P[j];
P[j]=P[m];
P[m]=tmp;
}
}
}
void print(int P[],int n)
{
int i;
for (i=1;i<=n;i++)
printf("%d ",P[i]);
printf("/n");
}
楼主拿去可以做一些优化改写...