Python uses the Backtracking Method subset tree template to solve the stair climb problem example, python stair climb

Source: Internet
Author: User

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

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.