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]