Python實現 爬樓梯 的方法

2021-08-26 20:19:14 字數 1106 閱讀 9890

你需要攀爬乙個有n個台階的梯子

每一次你只能走1步或者兩步,計算有多少中不同的登頂方式

注意:n必為正整數

example 1:

input: 2

output: 2

explanation: there are two ways to climb to the top.

1. 1 step + 1 step

2. 2 steps

example 2:

input: 3

output: 3

explanation: there are three ways to climb to the top.

1. 1 step + 1 step + 1 step

2. 1 step + 2 steps

3. 2 steps + 1 step

假設梯子有n層,那麼如何爬到第n層呢,因為每次只能怕1或2步,那麼爬到第n層的方法要麼是從第n-1層一步上來的,要不就是從n-2層2步上來的,所以遞推公式非常容易的就得出了:

dp[n] = dp[n-1] + dp[n-2]

def climbstairs(self, n):

""":type n: int

:rtype: int

"""if n<=2:

return n

temp_list = [0,1,2]

for i in range(3,n+1):

return temp_list[-1]

def climbstairs(self, n):

""":type n: int

:rtype: int

"""sum = 0

if n<=2:

return n

sum += self.climbstairs(n-1)

sum += self.climbstairs(n-2)

return sum

演算法題來自:

python爬樓梯遞迴 爬樓梯(Python3)

假設你正在爬樓梯。需要 n 階你才能到達樓頂。每次你可以爬 1 或 2 個台階。你有多少種不同的方法可以爬到樓頂呢?注意 給定 n 是乙個正整數。示例 1 輸入 2 輸出 2 解釋 有兩種方法可以爬到樓頂。1 階 1 階 和 2 階 解題思路 實現了兩種方法,但是第一種超出時間限制 因為遞迴的時候方...

python爬樓梯演算法 爬樓梯(Python3)

假設你正在爬樓梯。需要 n 階你才能到達樓頂。每次你可以爬 1 或 2 個台階。你有多少種不同的方法可以爬到樓頂呢?注意 給定 n 是乙個正整數。示例 1 輸入 2 輸出 2 解釋 有兩種方法可以爬到樓頂。1 階 1 階 和 2 階 解題思路 實現了兩種方法,但是第一種超出時間限制 因為遞迴的時候方...

爬樓梯 python Python3爬樓梯演算法示例

假設你正在爬樓梯。需要 n 步你才能到達樓頂。每次你可以爬 1 或 2 個台階。你有多少種不同的方法可以爬到樓頂呢?注意 給定 n 是乙個正整數。方案一 每一步都是前兩步和前一步的和 class solution object def climbstairs self,n type n int rt...