From fbf7a0b47242eb0d80e5c344cfc3f118e0beee6b Mon Sep 17 00:00:00 2001 From: giladwo <25708271+giladwo@users.noreply.github.com> Date: Mon, 3 Oct 2022 21:57:51 +0300 Subject: [PATCH 1/2] Simplify climbing stairs and use constant memory --- dynamic_programming/climbing_stairs.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index 048d57aed1be..bf537e8ff31c 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -30,11 +30,10 @@ def climb_stairs(n: int) -> int: ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 - dp = [0] * (n + 1) - dp[0], dp[1] = (1, 1) - for i in range(2, n + 1): - dp[i] = dp[i - 1] + dp[i - 2] - return dp[n] + previous, current = 1, 1 + for _ in range(n - 1): + current, previous = current + previous, current + return current if __name__ == "__main__": From 0d18a732e8fc7253d15f0b2965f40cbd9676bfb9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 30 Oct 2022 10:54:15 +0100 Subject: [PATCH 2/2] number_of_steps --- dynamic_programming/climbing_stairs.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index bf537e8ff31c..d6273d025f08 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -1,20 +1,20 @@ #!/usr/bin/env python3 -def climb_stairs(n: int) -> int: +def climb_stairs(number_of_steps: int) -> int: """ LeetCdoe No.70: Climbing Stairs - Distinct ways to climb a n step staircase where - each time you can either climb 1 or 2 steps. + Distinct ways to climb a number_of_steps staircase where each time you can either + climb 1 or 2 steps. Args: - n: number of steps of staircase + number_of_steps: number of steps on the staircase Returns: - Distinct ways to climb a n step staircase + Distinct ways to climb a number_of_steps staircase Raises: - AssertionError: n not positive integer + AssertionError: number_of_steps not positive integer >>> climb_stairs(3) 3 @@ -23,15 +23,15 @@ def climb_stairs(n: int) -> int: >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... - AssertionError: n needs to be positive integer, your input -7 + AssertionError: number_of_steps needs to be positive integer, your input -7 """ assert ( - isinstance(n, int) and n > 0 - ), f"n needs to be positive integer, your input {n}" - if n == 1: + isinstance(number_of_steps, int) and number_of_steps > 0 + ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" + if number_of_steps == 1: return 1 previous, current = 1, 1 - for _ in range(n - 1): + for _ in range(number_of_steps - 1): current, previous = current + previous, current return current