Example python using the backtracking subset tree template to solve stair climbing problems

Source: Internet
Author: User
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

Related Article

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.