Topic DescriptionWe all know the Fibonacci sequence, and now you're going to need to enter an integer n, so you output the nth item in the Fibonacci sequence.
n<=39
Method 1:
Cycle.
#-*-Coding:utf-8-*-
class Solution:
def Fibonacci (self, N):
# Write code here
if n <= 2:
return [0, 1, 1] [N]
Second = 1, 1 while
n > 2: A,
second = Second, A/second n-
= 1 return
second
Run Time: 25ms
Memory footprint: 5728k
Method 2: recursion.
#-*-Coding:utf-8-*-
class Solution:
def Fibonacci (self, N):
# Write code here
if n = 0:
retur N 0
elif n = 1: return
1
else: return
self. Fibonacci (n-1) + self. Fibonacci (n-2)
Not saved through your code
Run Timeout: Your program failed to run at the end of the specified time, please check if the loop is wrong or the algorithm is too complex to spend.
Case Pass rate is 0%
Obviously, time complexity and space complexity are too large when implemented using recursive methods. Because the function calls itself, and function calls have time and space consumption: every time a function call, you need to allocate space in the memory stack to save parameters, return address and temporary variables, and push data into the stack and pop-up data will take time.