全排列

利用递归的思想和python的deque,产生一个字符串的所有排列组合

from collections import deque
def generate_permutations(string):
    if len(string) == 1:
        return deque([string])
    permutations = generate_permutations(string[1:])
    for i in range(len(permutations)):
        permutation = permutations.pop()
        for j in range(len(permutation)):
            permutations.appendleft(permutation[:j] + string[0] + permutation[j:])
        permutations.appendleft(permutation + string[0])
    return permutations
    

 全排列问题比较朴素的方法是用回溯的思想,也就是访问一个多叉树。

假如有[1,2,3], 求这个数组的全排列。那么可以将求解的过程抽象为遍历多叉树的过程,当遍历到树的根节点时,回收结果。

def gen_permutation(lst):
    record = []
    __gen_permutation(lst, "", record)
    return record

def __gen_permutation(lst, ans, record):
    if len(ans) == len(lst):
        record.append(ans)
        return 
    for i in range(len(lst)):
        if str(lst[i]) not in ans:
            __gen_permutation(lst, ans+str(lst[i]), record)

 

posted @ 2018-05-31 20:28  AcodingDog  阅读(750)  评论(0编辑  收藏  举报