[7] wins the offer. Fibonacci number [by Python]

Title Description

We all know that Fibonacci number, and now asked to enter an integer n, you export item n Fibonacci Fibonacci number sequence.

n<=39


method 1:

cycle.


       
       
  1. # -*- coding:utf-8 -*-
  2. class Solution:
  3. def Fibonacci(self, n):
  4. # write code here
  5. if n <= 2:
  6. return [ 0, 1, 1][n]
  7. first, second = 1, 1
  8. while n > 2:
  9. first, second = second, first + second
  10. n -= 1
  11. return second

Running time: 25ms

Take up memory: 5728k


Method 2:

Recursion.

       
       
  1. # -*- coding:utf-8 -*-
  2. class Solution:
  3. def Fibonacci(self, n):
  4. # write code here
  5. if n == 0:
  6. return 0
  7. Elif N == 1 :
  8. return 1
  9. else:
  10. return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
Fail
Your code has been saved
run timeout: Your program failed to run at the end of the specified time, check to see if there is wrong or cycle through the large complex algorithms.
case was 0.00% by

Obviously, when implemented using a recursive method, time and space complexity of the complex is too big. Since the function calls itself, but a function call is time and space consumption: every function call, you need the memory stack space allocated to save the parameters, return address and temporary variables, and to the stack pressed into data and pop-up data needs time.


Title Description

We all know that Fibonacci number, and now asked to enter an integer n, you export item n Fibonacci Fibonacci number sequence.

n<=39


method 1:

cycle.


    
    
  1. # -*- coding:utf-8 -*-
  2. class Solution:
  3. def Fibonacci(self, n):
  4. # write code here
  5. if n <= 2:
  6. return [ 0, 1, 1][n]
  7. first, second = 1, 1
  8. while n > 2:
  9. first, second = second, first + second
  10. n -= 1
  11. return second

Running time: 25ms

Take up memory: 5728k


Method 2:

Recursion.

    
    
  1. # -*- coding:utf-8 -*-
  2. class Solution:
  3. def Fibonacci(self, n):
  4. # write code here
  5. if n == 0:
  6. return 0
  7. Elif N == 1 :
  8. return 1
  9. else:
  10. return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
Fail
Your code has been saved
run timeout: Your program failed to run at the end of the specified time, check to see if there is wrong or cycle through the large complex algorithms.
case was 0.00% by

Obviously, when implemented using a recursive method, time and space complexity of the complex is too big. Since the function calls itself, but a function call is time and space consumption: every function call, you need the memory stack space allocated to save the parameters, return address and temporary variables, and to the stack pressed into data and pop-up data needs time.


Guess you like

Origin blog.csdn.net/qq_33487726/article/details/91975885