[python] Climbing stairs - recursive analysis (super detailed)

Climbing Stairs - Recursive Analysis

Suppose you are climbing stairs. It takes n steps before you can reach the top of the building. You can climb 1 or 2 steps at a time. How many different ways can you get to the top of the building? Note: The given n is a positive integer.

Example 1:
Input: 1
Output: 1
Explanation: There is a way to get to the top of a building.
Method 1: 1 stage

Example 2:
Input: 2
Output: 2
Explanation: There are two ways to get to the top of the building.
Method 1: 1 step + 1 step
Method 2: 2 steps


Continue to analyze backwards, we will get:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top of the building.
Method 1: Tier 1 + Tier 1 + Tier 1
Method 2: Tier 1 + Tier 2
Method 3: Tier 2 + Tier 1

Input: 4
Output: 5
Explanation: There are 5 ways to climb to the top of the building.
Method 1: Step 1 + Step 1 + Step 1 + Step 1
Method 2: Step 1 + Step 1 + Step 2
Method 3: Step 1 + Step 2 + Step 1 Method 4
: Step 2 + Step 1 + Step 1
Method 5: 2nd stage + 2nd stage

Input: 5
Output: 8
Explanation: There are 5 ways to climb to the top of the building.
Method 1: Step 1 + Step 1 + Step 1 + Step 1 + Step 1
Method 2: Step 1 + Step 1 + Step 1 + Step 2 Method
3: Step 1 + Step 1 + Step 2 + Step 1
Method 4: Step 1 + 2 steps + 1 step + 1 step
Method 5: 1 step + 2 steps + 2 steps
Method 6: 2 steps + 1 step + 1 step + 1 step
Method 7: 2 steps + 1 step + 2 steps
Method 8: 2 steps + 2nd stage + 1st stage

To summarize the above:

When there are 1 stairs, there is 1 way, expressed as: f(1) = 1
When there are 2 stairs, there are 2 ways, expressed as: f(2) = 2
When there are 3 stairs, there are 3 ways , expressed as: f(3) = f(2) + f(1) = 3
When there are 4 stairs, there are 5 ways, expressed as: f(4) = f(3) + f(2) = 5
When there are 5 floors of stairs, there are 8 methods, expressed as: f(5) = f(4) + f(3) = 8 ... (
and so on)
When there are n floors of stairs, there are f(n) methods, Expressed as: f(n) = f(n-1) + f(n-2) = ?

The python code is as follows:

def digui(n):
    if n == 1:
        return 1
    if n == 2:
        return 2
    return digui(n - 1) + digui(n - 2)

print(digui(5))

operation result:

8

Flowchart thinking analysis:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44244190/article/details/131893154