Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of climbing stairs by python

Shulou Source: shulou.com Published: 2022-05-31 14:07:45 09月14日 Update

This article mainly introduces the relevant knowledge of python how to solve the stair climbing problem, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this python article on how to solve the stair climbing problem. Let's take a look at it.

[title]

Suppose you are climbing the stairs. You need step n to get to the roof.

You can climb one or two steps at a time. How many different ways do you have to climb to the roof?

Note: given n is a positive integer.

Example 1:

Enter: 2

Output: 2

Explanation: there are two ways to climb to the roof.

1. Order 1 + 1

2. Order 2

Example 2:

Enter: 3

Output: 3

Explanation: there are three ways to climb to the roof.

1. 1 order + 1 order + 1 order

2. Order 1 + 2

3. Order 2 + 1

[ideas]

Climb to step I, the last step may be one step from step I-1, or two steps from step I-2.

We use dp array storage, and dp [I] represents the total number of possible ways to climb to the first step, then dp [I] = dp [I-1] + dp [I-2].

[code]

Python version

Class Solution:

Def climbStairs (self, n: int)-> int:

If n < 3:

Return n

# dp [I] = DP [I-1] + DP [I-2]

Dp = [1,2]

For i in range (2, n):

Dp.append (DP [I-1] + dp [I-2])

Return dp [- 1] this is the end of the article on "how to solve the problem of climbing stairs by python". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to solve the problem of climbing stairs by python". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Steps stairs problems methods roofs knowledge content examples articles explanations inputs outputs differences code values ideas totals simple operations arrays integers Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Linux Apple Shulou Technology OPPO Reno