update 70
This commit is contained in:
parent
cf0b925c41
commit
fd5fc4ace5
46
leetcode/70.py
Normal file
46
leetcode/70.py
Normal file
@ -0,0 +1,46 @@
|
||||
# Climbing Stairs
|
||||
|
||||
|
||||
class Solution:
|
||||
def climbStairs(self, n: int) -> int:
|
||||
"""
|
||||
# Fibonacci sequence
|
||||
# too slow: O(n)
|
||||
if n <= 2:
|
||||
return n
|
||||
|
||||
first, second = 1, 2
|
||||
for _ in range(3, n + 1):
|
||||
first, second = second, first + second
|
||||
|
||||
return second
|
||||
"""
|
||||
|
||||
# DP recurion
|
||||
# fastest
|
||||
from functools import cache
|
||||
|
||||
@cache
|
||||
def f(n):
|
||||
if n <= 2:
|
||||
return n
|
||||
return f(n - 1) + f(n - 2)
|
||||
|
||||
return f(n)
|
||||
|
||||
"""
|
||||
# Matrix Power Solution
|
||||
# O(log n) but slower???
|
||||
if n <= 2:
|
||||
return n
|
||||
|
||||
import numpy as np
|
||||
|
||||
M = np.array([[1, 1], [1, 0]])
|
||||
A = np.array([[1, 1]]) @ np.linalg.matrix_power(M, n - 2) @ np.array([[1], [1]])
|
||||
return A[0, 0]
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(Solution().climbStairs(91))
|
Loading…
x
Reference in New Issue
Block a user