Python uses the Backtracking Method subset tree template to solve the stair climb problem example, python stair climb
The example in this article describes how to use a subset tree template of the Backtracking Method to Solve the stair climb problem in Python. We will share this with you for your reference. The details are as follows:
Problem
A certain stair has n-tier steps. Each step can only take 1 or 2 steps. How many ways can I climb the stairs from the bottom up?
Analysis
This problem was previously solved by the Division and Control Law. However, here I want to solve it with the subset tree template of the Backtracking Method.
The method for analyzing the element-state space: each step is an element, and the number of steps that can be taken [1, 2] is its state space. It is not hard to see that the elements are not fixed, and the state space is fixed.
Directly add the code.
Code
'''Stair cret''' n = 7 # stair creden x = [] # A solution (the length is not fixed. An array of 1-2 indicates the number of steps taken in this step) X = [] # A set of solutions # conflict Detection def conflict (k): global n, x, X # The sum of the steps in the decomposition 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): # Go To step k global n, x, X if sum (x) = n: # The sum of all steps taken is equal to the total number of stairs print (x) # X. append (x [:]) # Save (a solution) else: for I in [1, 2]: # the state space of the element in step k is [1, 2] x. append (I) if not conflict (k): # pruning climb_stairs (k + 1) x. pop () # backtracking # test climb_stairs (0) # Step 1