Python uses the Backtracking Method subset tree template to solve the full arrangement problem example, python backtracking

Source: Internet
Author: User

Python uses the Backtracking Method subset tree template to solve the full arrangement problem example, python backtracking

This article describes how Python solves the full arrangement problem based on the subset tree template of the Backtracking Method. We will share this with you for your reference. The details are as follows:

Problem

Implement the full arrangement of the four elements 'A', 'B', 'C', and 'D.

Analysis

You can directly apply the arrangement tree template to this issue.

However, this document uses the subset tree template. The analysis is as follows:

A solution x is an arrangement of n elements. Obviously, the length of the solution x is fixed, n.
We consider this as follows: For solution x, we first arrange 0th elements x [0], and then 1st elements x [1],..., when it comes to the K-1 element x [k-1], all the remaining unarranged elements will be seen as the state space of the element x [k-1], traversing it.

Now, you can apply the subset tree template.

Code

'''Use a subset tree to realize full arrangement ''' n = 4a = ['A', 'B', 'C ', 'D'] x = [0] * n # A solution (n yuan 0-1 array) X = [] # A group of solutions # conflict Detection: No def conflict (k ): global n, x, X, a return False # No conflict # use a subset tree template to implement full arrangement def perm (k): # Reach the k-th element global n, a, x, X if k> = n: # print (x) # X. append (x [:]) # Save (a solution) else: for I in set (a)-set (x [: k]): # traverse, the remaining unarranged elements are treated as the state space of the element x [k-1] x [k] = I if not conflict (k): # pruning perm (k + 1) # testing perm (0) # Starting from x [0]

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: info-contact@alibabacloud.com 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.