Recursive solution for all permutations using the algorithm

Source: Internet
Author: User

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: 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.