Python-剑指Offer(五):Fibonacci数列

非递归,时间复杂度O(N)方法:

def fibonacci(n):
    f0, f1, f2 = 0, 1, 0
    if n == 0:
        return 0
    if n == 1:
        return 1
    i = 2
    while i <= n:
        f2 = f0 + f1
        f0 = f1
        f1 = f2
        i += 1
    return f2

递归方法:

def f(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return f(n-2) + f(n-1)

猜你喜欢

转载自blog.csdn.net/qq_35134080/article/details/87901322
今日推荐