Skip to content

Commit 827ba4c

Browse files
committed
Climbing stairs
1 parent 825fe2b commit 827ba4c

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

70.climbing_stairs/stairs.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 70. Climbing stairs
2+
# Topics: 'Math', 'Dynamic Programming', 'Memoization'
3+
4+
# You are climbing a staircase. It takes n steps to reach the top.
5+
6+
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
7+
8+
9+
10+
# Example 1:
11+
12+
# Input: n = 2
13+
# Output: 2
14+
# Explanation: There are two ways to climb to the top.
15+
# 1. 1 step + 1 step
16+
# 2. 2 steps
17+
18+
# Example 2:
19+
20+
# Input: n = 3
21+
# Output: 3
22+
# Explanation: There are three ways to climb to the top.
23+
# 1. 1 step + 1 step + 1 step
24+
# 2. 1 step + 2 steps
25+
# 3. 2 steps + 1 step
26+
27+
28+
29+
# Constraints:
30+
31+
# 1 <= n <= 45
32+
33+
from typing import List
34+
35+
class Solution:
36+
# time and space O(n)
37+
def climbStairs(self, n: int) -> int:
38+
memo = [0]*(n+1)
39+
return self.climb(n, memo)
40+
41+
def climb(self, n: int, memo: List[int]) -> int:
42+
if n <= 1:
43+
return 1
44+
if memo[n]:
45+
return memo[n]
46+
memo[n] = self.climb(n-1, memo) + self.climb(n-2, memo)
47+
return memo[n]
48+
49+
# bruteforce solution O(2^n)
50+
# def climbStairs(self, n: int) -> int:
51+
# if n <= 1:
52+
# return 1
53+
# return self.climbStairs(n-1) + self.climbStairs(n-2)

70.climbing_stairs/test_stairs.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import unittest
2+
from stairs import Solution
3+
4+
class TestClimbStairs(unittest.TestCase):
5+
def setUp(self):
6+
self.s = Solution()
7+
def test_small_values(self):
8+
self.assertEqual(self.s.climbStairs(1), 1)
9+
self.assertEqual(self.s.climbStairs(2), 2)
10+
self.assertEqual(self.s.climbStairs(3), 3)
11+
self.assertEqual(self.s.climbStairs(4), 5)
12+
13+
def test_medium_values(self):
14+
# Fibonacci sequence logic
15+
self.assertEqual(self.s.climbStairs(5), 8)
16+
self.assertEqual(self.s.climbStairs(6), 13)
17+
self.assertEqual(self.s.climbStairs(7), 21)
18+
19+
def test_larger_value(self):
20+
# Warning: with naive recursion this may run slow!
21+
self.assertEqual(self.s.climbStairs(10), 89)
22+
23+
def test_typical_leetcode_examples(self):
24+
self.assertEqual(self.s.climbStairs(2), 2)
25+
self.assertEqual(self.s.climbStairs(3), 3)
26+
27+
28+
if __name__ == "__main__":
29+
unittest.main()

0 commit comments

Comments
 (0)