mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update climbing_stairs.py
This commit is contained in:
parent
bce645eb9e
commit
784b8a8698
@ -10,38 +10,42 @@ In how many distinct ways can you climb to the top?
|
|||||||
|
|
||||||
|
|
||||||
def climb_stairs_o2n(n: int) -> int:
|
def climb_stairs_o2n(n: int) -> int:
|
||||||
|
|
||||||
if n == 0 or n == 1:
|
if n == 0 or n == 1:
|
||||||
return 1
|
return 1
|
||||||
return climb_stairs_o2n(n-1) + climb_stairs_o2n(n-2)
|
return climb_stairs_o2n(n-1) + climb_stairs_o2n(n-2)
|
||||||
|
|
||||||
|
|
||||||
|
def climb_stairs_memoization(n: int) -> int:
|
||||||
|
|
||||||
def helper(n: int, memo: dict[int, int]) -> int:
|
memo = {}
|
||||||
|
|
||||||
|
def helper(n: int, memo: dict[int, int]) -> int:
|
||||||
if n == 0 or n == 1:
|
if n == 0 or n == 1:
|
||||||
return 1
|
return 1
|
||||||
if n not in memo:
|
if n not in memo:
|
||||||
memo[n] = helper(n-1, memo) + helper(n-2, memo)
|
memo[n] = helper(n-1, memo) + helper(n-2, memo)
|
||||||
return memo[n]
|
return memo[n]
|
||||||
|
|
||||||
def climb_stairs_memoization(n: int) -> int:
|
|
||||||
memo = {}
|
|
||||||
return helper(n, memo)
|
return helper(n, memo)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def climb_stairs_optimized(n: int) -> int:
|
def climb_stairs_optimized(n: int) -> int:
|
||||||
|
|
||||||
if n == 0 or n == 1:
|
if n == 0 or n == 1:
|
||||||
return 1
|
return 1
|
||||||
prev, curr = 1, 1
|
prev, curr = 1, 1
|
||||||
|
|
||||||
for i in range(2, n+1):
|
for i in range(2, n+1):
|
||||||
temp = curr
|
temp = curr
|
||||||
curr = prev + curr
|
curr = prev + curr
|
||||||
prev = temp
|
prev = temp
|
||||||
|
|
||||||
return curr
|
return curr
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def climb_stairs_tabulation(n: int) -> int:
|
def climb_stairs_tabulation(n: int) -> int:
|
||||||
|
|
||||||
if n == 0 or n == 1:
|
if n == 0 or n == 1:
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
@ -50,11 +54,5 @@ def climb_stairs_tabulation(n: int) -> int:
|
|||||||
|
|
||||||
for i in range(2, n+1):
|
for i in range(2, n+1):
|
||||||
dp[i] = dp[i-1] + dp[i-2]
|
dp[i] = dp[i-1] + dp[i-2]
|
||||||
|
|
||||||
return dp[n]
|
return dp[n]
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
print(climb_stairs_o2n(4))
|
|
||||||
print(climb_stairs_memoization(4))
|
|
||||||
print(climb_stairs_optimized(4))
|
|
||||||
print(climb_stairs_tabulation(4))
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user