Blue Bridge Cup Daily One Question (8): Step 39 (python)

Topic:

Xiao Ming just finished watching the movie "The 39th Steps". When he left the cinema, he counted the number of steps in front of the auditorium, which happened to be 39!
Standing in front of the steps, he suddenly thought of another question:
if I only had to Can step up 1 or 2 steps. Take the left foot first, then alternate left and right. The last step is the right foot, which means that you have to take an even number of steps. So, how many different ways are there after 39 steps?
Please take advantage of the computer to help Xiao Ming find the answer.

Solution:
First define a two-dimensional array dp with 39 steps
to solve the left and right foot problem
. The meaning of dp[a][b] is divided into
dp[a][0] The number of solutions for the left foot to step on the ath step
dp[a ][1] is the number of plans for step a with the right foot

Then derive the recursive equation: dp[0][0] = 1 dp[0][1] = 0
because the left foot is up the stairs

After going up the second step is the right foot,
so dp[1][0] = 1
dp[1][1] = 1

A step on the left foot is stepped up from the previous step with the right foot in one step
or two steps up with the right foot in two
steps. A step on the right foot is stepped up from the previous step with the left foot in one step
or two steps with the left foot in two steps Step up

Count the number of plans for the thirty-ninth step on the right foot is the answer

Code:

import numpy
dp = numpy.zeros((39, 2))

dp[0][0] = 1
dp[0][1] = 0
dp[1][0] = 1
dp[1][1] = 1

for i in range(2, 39):
    dp[i][0] = dp[i - 1][1] + dp[i - 2][1]
    dp[i][1] = dp[i - 1][0] + dp[i - 2][0]

print(dp[38][1])

Answer:
51167078

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112637862