Lintcode Python Entry-level topic Fibonacci sequence

Source: Internet
Author: User
Tags lintcode

Description of the original title:

Finds the nth number in the Fibonacci sequence.

The so-called Fibonacci sequence refers to:

    • The first 2 numbers are 0 and 1.
    • The number of I is the number I-1 and the number I-2.

The first 10 digits of the Fibonacci sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Topic Analysis:

The beginning of the idea, by recursively implementing output fib (n-1) +fib (n-2) value calculation, the principle is correct, the algorithm is high complexity, resulting in a running time exceeding the Lintcode limit:

Class solution:    # @param n:an integer    # @return an integer f (n)    # recursive implementation    def Fibonacci (self, N):        If n = = 1:            return 0        elif n = = 2:            return 1        else:            return Self.fibonacci (n-1) + Self.fibonacci (n-2)

Modified to an iterative implementation, the Fibonacci number is saved to the list, loop n-2 times, each time the last element of the sequence [-1] and the penultimate element [-2] is added to the list, and finally return to the last element of the list ~

Class solution:    # @param n:an integer    # @return an integer f (n)   # implement    def Fibonacci (self, n) through the For loop iteration:        num = [0,1]        if n = = 1:            return 0        elif n ==1:            return 1 for I in        Range (0,n-2):            num.append (Num[-1] + num[-2])        return Num[-1]

  

  

Lintcode Python Entry-level topic Fibonacci sequence

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.