Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 43b8ac1

Browse files
Climbing Stairs
1 parent bc097f1 commit 43b8ac1

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

‎70-climbing-stairs.py

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,36 @@
2222
2. 1 step + 2 steps
2323
3. 2 steps + 1 step
2424
"""
25-
class Solution(object):
26-
def climbStairs(self, n):
27-
if n == 1:
28-
return 1
29-
a,b = 1,2
30-
for _ in range(2,n):
31-
a,b = b, a+b
32-
return b
25+
class Solution:
26+
def climbStairs(self, n: int) -> int:
27+
if n <= 2:
28+
return n
29+
30+
second_last_stair, last_stair = 1, 2
31+
32+
for _ in range(3, n+1):
33+
second_last_stair, last_stair = last_stair, last_stair + second_last_stair
34+
35+
return last_stair
36+
37+
38+
class Solution1:
39+
def climbStairs(self, n: int) -> int:
40+
return self.helper(n, {})
41+
42+
def helper(self, n, memo):
43+
if n <= 2:
44+
return n
45+
46+
if n not in memo:
47+
memo[n] = self.helper(n-1, memo) + self.helper(n-2, memo)
48+
49+
return memo[n]
50+
51+
52+
# TLE
53+
class Solution2:
54+
def climbStairs(self, n: int) -> int:
55+
if n <= 2:
56+
return n
57+
return self.climbStairs(n-1) + self.climbStairs(n-2)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /