This article mainly introduces the use of the backtracking subset tree template to solve the stair climbing problem, simply explains the stair climbing problem and gives the Python backtracking subset tree template to solve the stair climbing problem related operation skill, needs the friend to consult under
The examples in this article describe how Python uses the backtracking subset tree template to solve stair climbing problems. Share to everyone for your reference, as follows:
Problem
A staircase has n-level steps, each step can only walk 1 steps, or 2 steps. How many ways are there to climb stairs from the bottom up?
Analysis
This problem has been solved by division and administration before. But here I'm going to use the backtracking subset tree template to solve it.
The element of sacrifice-state space analysis Dafa: Each step is an element, the number of steps that can be walked is its state space. It is not difficult to see that the element is not fixed and the state space fixed.
directly on the code.
Code
' Climb the stairs ' n = 7 # Stair Order x = [] # A solution (length not fixed, 1-2 array, number of steps to represent the walk) X = [] # A set of solutions # Conflict Detection def conflict (k): global N, x, x # The sum of the steps in part of the step exceeds the total number of steps if sum (x[:k+1]) > N: return True return False # no conflict # backtracking (recursive version) def climb_stairs (k): # Walk the K step global N, x, x if sum (x) = = N: # The sum of all steps that have been taken is equal to the total number of steps of the staircase print (x) #X. Append (x[:]) # Save (a solution) else: For i in [1, 2]: # K Step this element has a state space of [x.append] (i) if not conflict (k): # Pruning climb_stairs (k+1) X.pop () # backtesting # Test Climb_stairs (0) # Take the No. 0 step