[7] Offer to prove safety Fibonacci columns python achieve

Title Description

We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39


1. recursion


  1. Analysis
    Fibonacci standard formula of Number is: F (1) = 1, F (2) = 1, F (n) = F (n-1) + (n> = 3 F (n-2), n ∈N *)
    according to the formula directly write:

  2. Code

  3. Complexity
    Time Complexity: O ( 2 n ) O ( 2 n ) O (2 ^ n) O (2 n)
    spatial complexity: O ( 1 ) O ( 1 ) O (1) O (1)

2. Optimize recursive


  1. Analysis of
    recursive calculation is repeated a lot of the same data, we use an array to store the result up 8!

  2. Code

  3. Complexity
    time complexity: O (n) O (n )
    space complexity: O (n) O (n )

3. Optimizing Storage


  1. Analysis of
    fact, we can find a time to use the two most recent numbers, so we can store only the last two numbers
  • sum of n items stored value
  • one stored value of the n-1 items
  • the stored value of the two items n-2
  1. Code
# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        preNum = 1
        prePreNum = 0

        result = 0
        if n == 0:
            return 0
        if n == 1:
            return 1
        # [0,1,1,2]
        for i in range(2,n+1):

            result = preNum + prePreNum
            prePreNum = preNum
            preNum = result

        return result
  1. Complexity:
    time complexity: O (n) O (n )
    complexity of space: O (1) O (1 )
发布了99 篇原创文章 · 获赞 6 · 访问量 4001

Guess you like

Origin blog.csdn.net/weixin_42247922/article/details/103911584