Sword refers to offer the Python version-Fibonacci sequence __python

Source: Internet
Author: User
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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.