In Python there is a module called Itertools, using this module can quickly solve permutation problem, just friends ask how to perfection permutation problem, can not use the built-in module to do, so ... Think logically, using recursive implementation is relatively simple.
The following is a simple implementation code:
1 #!/usr/bin/env python2 #Encoding:utf-83 #__author__: Huxianglin4 #DATE:2016/9/25 12:095 #blog:http://huxianglin.cnblogs.com/http://xianglinhu.blog.51cto.com/6 7 defPerm (list,stack):8 if notlist:9 Print(Stack) # to the end of the tree, output the resultTen Else: # When there is no leaf node to the tree, use recursion to continue looking down. One forIinchRange (len (list)): A stack.append (List[i]) - delList[i] - Perm (List,stack) the List.insert (I,stack.pop ()) - -list=[1,2,3] -stack=[] +Perm (List,stack)
The above defines two lists, a list of the data that needs to be fully arranged, the other list is used as a stack, you can recursively think of it as a tree, at the top of which is to include all the worthwhile list, and then from the list to take off a value, to the second layer, when the stack is stored in the data that is taken out, A value in this layer is less than the value just taken off, until the end of the list is empty, the stack is the result of this arrangement, the results printed out, so bad understanding, draw a diagram to explain the next ...
OK, this is not easy to understand, so it can also explain why recursion is actually a tree ... Of course, you can also use stacks instead of recursive implementations, but ... It hasn't been implemented yet. The difference is almost the difference between recursive traversal and non-recursive traversal of a tree.
Recursive solution for all permutations using the algorithm