Skip to content

Commit dbde40d

Browse files
committed
climing stairs solution
1 parent b9b9d91 commit dbde40d

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

climbing-stairs/yerim01.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Goal: Given n steps, return the number of distinct ways you can climb to the top.
2+
# Constraints:
3+
# - You can climb either 1 or 2 steps at each time.
4+
# - 1 <= n <= 45
5+
# Approach:
6+
# f(n) = number of ways to reach step n.
7+
# The last move must be from step n-1 or step n-2.
8+
# Therefore, f(n) = f(n-1) + f(n-2).
9+
# Base case - f(1) = 1, f(2) = 2.
10+
# Use two variables prev1&prev2 to track the number of of f(n-1)&f(n-2).
11+
# Iterate a loop, staring from 3.
12+
# Store prev1 into temp.
13+
# Update prev1&prev2.
14+
# Return prev1.
15+
16+
# Time complexity: O(n)
17+
# - We iterate once
18+
# Space complexity: O(1)
19+
# - Only using variables
20+
21+
class Solution:
22+
def climbStairs(self, n: int) -> int:
23+
if n <= 2:
24+
return n
25+
26+
prev1 = 2
27+
prev2 = 1
28+
29+
for i in range(3, n+1):
30+
temp = prev1
31+
prev1 = prev2 + prev1
32+
prev2 = temp
33+
34+
return prev1

0 commit comments

Comments
 (0)