递归实现全排列python

python递归实现"abcd"字符串全排列

1.保持a不动,动bcd
2.保持b不动,动cd
3.保持c不动,动d

def pailie(head="",string=""):
    if len(string)>1:
        for father_string in string:
            pailie(head+father_string,string.replace(father_string,"")) #关键一点:将头和尾全部传下去
    else:
        print(head+string)


pailie(string="abcd")

python递归实现"abad"字符串全排列

与上一个两个不同,一是,第一个a排完顺序后,下一个a不能再排,二是替换的时候不能把重复的也替换掉

def pailie(head="",string=""):
    if len(string)>1:
        for num,father_string in enumerate(string):
            if father_string in string[0:num]:#如果字符与前面的重复说明拍过顺序了
                continue
            pailie(head+father_string,string.replace(father_string,"",1))#只能替换一次
    else:
        print(head+string)

pailie(string="abca")

posted @ 2019-07-06 16:51  会飞的两棵树  阅读(2001)  评论(0编辑  收藏  举报