请问如何列遍a,b,c,d,e,f六个字符串? 结果像这样的: a,b,c,d,e,f b,c,d,e,f ... f,a,b,c,d,e

如题所述

用python写了一个。思路是摘抄的别人的。http://zhidao.baidu.com/question/136206758.html
假设我们求permute(abc)的全排列。permute(abc)的全排列=a+permute(bc)和b+permute(ac)和c+permute(ab)=…………….依次类推。所以就可以用递归做。而将abc拆分成a+bc,b+ac,c+ab的

总共有720组。所以可以用简单的3个字母来思考,比较方便。

def permute(s):
sLen=len(s)
if sLen==1:
return s
x=[]
for i in range(0,sLen):
p=permute(s[0:i]+s[i+1:])
for t in p:
if type(t)==list:
x.append([s[i]]+t)
else:
x.append([s[i]]+[t])
return x

if __name__=='__main__':
x=permute([i for i in 'abcdef'])
print "number:",len(x)
#print "permute:",x追问

太多组了,我只要6组而已。能不能再优化一下代码?

追答

这个倒要请教你一下,怎么优化?不用递归,这个很难处理的。用了递归,你就很难控制了。
当然,只打印出前面6组也可以。甚至手工求都很容易,也不用什么狗屁编程了。
abcdfe
abcedf
abcefd
abcfde
abcfed

追问

你的递归只是变换后面而已,而我的要求是:
a,b,c,d,e,f
b,c,d,e,f,a
c,d,e,f,a,b
d,e,f,a,b,c
e,f,a,b,c,d
f,a,b,c,d,e

追答

如果只是你的追问的要求,那就没有上问问来问的意义了。不过就是把数组元素左移,最左边的放到最后,重复这种操作数组共元素个数次。只要学过c语言数组的都会。
另外也没有这么用省略号的吧,把追问的要求放在开始的问里面不就好了?因为按照你的意思,只能让人理解为想获得所有项的全排列。获得这种全排列有一定难度,想要简洁的求出来需要用到递归,并且要注意保存返回值。下面的程序就是符合你的补充要求的。

#include
#include

int main(int argc,char *argv[])
{
char ch[]={'a','b','c','d','e','f'};
char tmpCh;
int len=sizeof(ch)/sizeof(ch[0]);
int i=0;
int j=0;

for(i=0;i<len;i++)
{
/*print the array*/
for(j=0;j<len;j++)
{
printf("%c",ch[j]);
}
printf("\n");

/*exchange the first and the last*/
tmpCh=ch[0];
for(j=0;j<len-1;j++)
{
ch[j]=ch[j+1];
}
ch[len-1]=tmpCh;
}
return 0;
}

温馨提示:答案为网友推荐,仅供参考
相似回答