|
| 1 | +# https://leetcode.com/problems/climbing-stairs/ |
| 2 | + |
| 3 | +# Intuition, I can reach each step from n-1 and n-2, add the ways to reach them |
| 4 | +# It is a fibonacci sequence |
| 5 | +import timeit |
| 6 | + |
| 7 | +# Runtime: 42 ms, faster than 59.35% of Python3 online submissions for Climbing Stairs. |
| 8 | +# Memory Usage: 13.8 MB, less than 57.08 % of Python3 online submissions for Climbing Stairs. |
| 9 | + |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def climbStairs(self, n: int) -> int: |
| 13 | + # Between 0 and 2, return the value itself |
| 14 | + if n < 3: |
| 15 | + return n |
| 16 | + # Initialize pointers with the seeds |
| 17 | + pp, p = 1, 1 |
| 18 | + # Iterate from 2 to n-1 |
| 19 | + for _ in range(n): |
| 20 | + # Increase the values of the next table positions |
| 21 | + # 0 1 2 3 5 8 13 ... |
| 22 | + pp, p = p, p + pp |
| 23 | + # Return the memoized value of adding up n-1 + n-2 up to n |
| 24 | + return pp |
| 25 | + |
| 26 | + |
| 27 | +def test(): |
| 28 | + executors = [ |
| 29 | + {'executor': Solution, 'title': 'Solution', }, |
| 30 | + ] |
| 31 | + tests = [ |
| 32 | + [0, 0], |
| 33 | + [1, 1], |
| 34 | + [2, 2], |
| 35 | + [3, 3], |
| 36 | + [5, 8], |
| 37 | + ] |
| 38 | + for executor in executors: |
| 39 | + start = timeit.default_timer() |
| 40 | + for _ in range(int(float('1'))): |
| 41 | + for t in tests: |
| 42 | + sol = executor['executor']() |
| 43 | + result = sol.climbStairs(t[0]) |
| 44 | + expected = t[1] |
| 45 | + assert result == expected, f'{result} != {expected}' |
| 46 | + stop = timeit.default_timer() |
| 47 | + used = str(round(stop - start, 5)) |
| 48 | + res = "{0:20}{1:10}{2:10}".format( |
| 49 | + executor['title'], used, "seconds") |
| 50 | + print(f"\033[92m» {res}\033[0m") |
| 51 | + |
| 52 | + |
| 53 | +test() |
0 commit comments