From 30f2c6bc1763bb3cfe607707f96b1d9047a3d2b3 Mon Sep 17 00:00:00 2001 From: Verolilo <57696907+Verolilo@users.noreply.github.com> Date: Mon, 14 Feb 2022 14:15:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B00070.=E7=88=AC=E6=A5=BC?= =?UTF-8?q?=E6=A2=AF.md=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新0070.爬楼梯.md python版本,添加了O(1)复杂度的python代码 --- problems/0070.爬楼梯.md | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 7f47a991..da19ea0e 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -256,16 +256,28 @@ public int climbStairs(int n) { ### Python ```python +# 空间复杂度为O(n)版本 class Solution: def climbStairs(self, n: int) -> int: - # dp[i]表示爬到第i级楼梯的种数, (1, 2) (2, 1)是两种不同的类型 - dp = [0] * (n + 1) - dp[0] = 1 - for i in range(n+1): - for j in range(1, 3): - if i>=j: - dp[i] += dp[i-j] - return dp[-1] + # dp[i] 为第 i 阶楼梯有多少种方法爬到楼顶 + dp=[0]*(n+1) + dp[0]=1 + dp[1]=1 + for i in range(2,n+1): + dp[i]=dp[i-1]+dp[i-2] + return dp[n] + +# 空间复杂度为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