Offer- prove safety and recursive loop -python

- Fibonacci number -

We all know that Fibonacci number (1,1,2,3,5,8,13,21,34, ......), now asked to enter an integer n, you output the n-th Fibonacci term of Number of (from 0, the first 0 is 0).

n<=39

The Fibonacci recursion column satisfies the conditions: both F (n) = F (n-1) + F (n-2)

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        #递归法
        if n ==0:
            return 1
        elif n ==1:
            return 1
        else:
            return self.Fibonacci(n-1) +self.Fibonacci(n-2)
            

This simple and crude way, but allows for far too long.

Method 2

class Solution:
    def Fibonacci(self, n):
        a = [0,1,1]
        if n<3:
            return a[n]
        for i in range(3,n+1):
            a.append(a[i-1]+a[i-2])
        return a[n]

Step jump

Guess you like

Origin www.cnblogs.com/ansang/p/12040229.html