mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
更新0070.爬楼梯.md python版本
更新0070.爬楼梯.md python版本,添加了O(1)复杂度的python代码
This commit is contained in:
@ -256,16 +256,28 @@ public int climbStairs(int n) {
|
|||||||
### Python
|
### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
# 空间复杂度为O(n)版本
|
||||||
class Solution:
|
class Solution:
|
||||||
def climbStairs(self, n: int) -> int:
|
def climbStairs(self, n: int) -> int:
|
||||||
# dp[i]表示爬到第i级楼梯的种数, (1, 2) (2, 1)是两种不同的类型
|
# dp[i] 为第 i 阶楼梯有多少种方法爬到楼顶
|
||||||
dp = [0] * (n + 1)
|
dp=[0]*(n+1)
|
||||||
dp[0] = 1
|
dp[0]=1
|
||||||
for i in range(n+1):
|
dp[1]=1
|
||||||
for j in range(1, 3):
|
for i in range(2,n+1):
|
||||||
if i>=j:
|
dp[i]=dp[i-1]+dp[i-2]
|
||||||
dp[i] += dp[i-j]
|
return dp[n]
|
||||||
return dp[-1]
|
|
||||||
|
# 空间复杂度为O(1)版本
|
||||||
|
class Solution:
|
||||||
|
def climbStairs(self, n: int) -> int:
|
||||||
|
dp=[0]*(n+1)
|
||||||
|
dp[0]=1
|
||||||
|
dp[1]=1
|
||||||
|
for i in range(2,n+1):
|
||||||
|
tmp=dp[0]+dp[1]
|
||||||
|
dp[0]=dp[1]
|
||||||
|
dp[1]=tmp
|
||||||
|
return dp[1]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
|
Reference in New Issue
Block a user