Python uses the Backtracking Method subset tree template to solve the Sorting Problem example, python backtracking
This example describes how to use a subset tree template based on the Backtracking Method to Solve the Sorting Problem in Python. We will share this with you for your reference. The details are as follows:
Problem
Select m elements from n elements for arrangement. Each element can be repeated for up to r times. Here, m is [2, n], r is [1, m].
For example, three elements can be selected from four elements for arrangement. Each element can be repeated for r times at most.
Analysis
The length of the solution x is fixed, m.
For the solution x, the first row is the element x [0] With 0th positions, and the second row is the element x [1] with 1st positions. We regard the latter as a state of the former, that is, x [1] is a state of x [0 !!
Generally, we think of x [k] as a state in state space a of x [k-1], and all we have to do is traverse all States of a [k-1.
Apply the subset tree template.
Code
''' Selection problem: Select m elements from n elements for sorting. Each element can be repeated up to r times. Here, m is [2, n], r is [1, m]. Author: hhh5460 time: June 2, 2017 statement: This algorithm copyright belongs to hhh5460 all '''n' = 4a = ['A', 'B', 'C', 'C ', 'D'] m = 3 # pick 3 r = 2 from 4 # Each element can be repeated 2x = [0] * m # A solution (m yuan 0-1 array) X = [] # A group of solutions # conflict Detection def conflict (k): global n, r, x, X, a # The element x [k] in the decomposition cannot exceed r if x [: k + 1]. count (x [k])> r: return True return False # No conflict # use a subset tree template to implement the selection problem def perm (k): # Reach the k element global n, m, a, x, X if k = m: # print (x) # X. append (x [:]) # Save (a solution) else: for I in a: # traverse X [k-1] State Space a, other things are handed over to the pruning function! X [k] = I if not conflict (k): # pruning perm (k + 1) # testing perm (0) # sorting from x [0]