原創非遞迴實現全排列演算法
阿新 • • 發佈:2018-12-15
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'])