原创非递归实现全排列算法

Python语言描述

空间换时间的做法,借助队列去实现全排列

# ---------借助队列去实现全排列(原创)---------
from copy import copy
class Per_node(object):
    def __init__(self,elements):
        '''

        :param elements: 元素列表
        '''
        self.element_list = elements
        self.father_pop = []

class Per_que(object):
    def __init__(self):
        self.head=None

    def permutation(self,elements=[]):
        if len(elements)==0:
            print '无法排列!'
            return
        result_len = len(elements)
        self.head = Per_node(elements)
        node_list = [self.head]
        while len(node_list)!=0:
            node = node_list.pop()
            for i in xrange(len(node.element_list)):
                tmp_elements = copy(node.element_list)
                tmp_elements.pop(i)
                tmp_father_pop = copy(node.father_pop)
                tmp_father_pop.append(node.element_list[i])
                child_node = Per_node(tmp_elements)
                child_node.father_pop = tmp_father_pop
                if len(child_node.father_pop)==result_len:
                    print 'result:',child_node.father_pop
                node_list.append(child_node)

que = Per_que()
que.permutation(['a','b','c','d','e','f'])

猜你喜欢

转载自blog.csdn.net/qq_38322240/article/details/83113405