class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
My solution however is not working on Leetcode. Do you know why this is? Thank you so much!
I am trying to solve fibonacci sequence
You've chosen a poor algorithm. It's not that it's recursive, just horribly inefficient. Here's a more efficient recursive approach:
def climbStairs(self, n, res=1, nxt=1):
if n == 0:
return res
return self.climbStairs(n - 1, nxt, res + nxt)
This runs much faster than your code and can go a lot higher before getting a stack overflow. But it will eventually get a stack overflow. We might do better adding memoization but ultimately, a simple iterative solution would be easier:
def climbStairs(self, n): # doesn't use 'self', could be class method
if 0 <= n <= 1:
return 1
a = b = 1
for _ in range(n - 1):
a, b = b, a + b
return b
Your solution looks good but it's inefficient. You don't have to address if n==2 part. Keep it simple, like this:
class Solution:
def climbStairs(self, n: int) -> int:
if n == 0 or n == 1:
return 1
return self.climbStairs(n-1) + self.climbStairs(n-2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.