From 1b702cb5ad0e02179bb7a6b500725ef33f1bc0cc Mon Sep 17 00:00:00 2001 From: hiteshskp <51043123+hiteshskp@users.noreply.github.com> Date: Sat, 5 Apr 2025 20:34:24 +0530 Subject: [PATCH] Solution 3 to Climbing Stairs Problem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As 1 <= n <= 45 we can use Binet’s Formula (Fibonacci closed form) PS: this won't work for n>70 or 100 The "climb stairs" problem is equivalent to computing the nth Fibonacci number (with a slight index shift), where: F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) The number of ways to climb n stairs is the (n + 1)th Fibonacci number. --- Python/climbing-stairs.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Python/climbing-stairs.py b/Python/climbing-stairs.py index f1dcdfaec5..7ff54b51b5 100644 --- a/Python/climbing-stairs.py +++ b/Python/climbing-stairs.py @@ -42,3 +42,17 @@ def climbStairs(self, n): for i in xrange(n): prev, current = current, prev + current, return current + +# Time: O(1) +# Space: O(1) +""" +As 1 <= n <= 45 we can use Binet’s Formula (Fibonacci closed form) PS: this won't work for n>70 or 100 +The "climb stairs" problem is equivalent to computing the nth Fibonacci number (with a slight index shift), where: +F(0) = 0 +F(1) = 1 +F(n) = F(n-1) + F(n-2) +The number of ways to climb n stairs is the (n + 1)th Fibonacci number. +""" +class Solution3: + def climbStairs(self, n: int) -> int: + return round((((1 + 5**0.5)/2) ** (n + 1)) / 5**0.5)