【LeetCode】509、斐波那契数

509、Fibonacci Number斐波那契数

难度:简单

题目描述

  • 英文:

    The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0and 1. That is,

    1
    2
    F(0) = 0,   F(1) = 1
    F(N) = F(N - 1) + F(N - 2), for N > 1.

    Given N, calculate F(N).

  • 中文:

    斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 01 开始,后面的每一项数字都是前面两项数字的和。也就是:

    1
    2
    F(0) = 0,   F(1) = 1
    F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

    给定 N,计算 F(N)

  • 示例

    Example 1:

    1
    2
    3
    Input: 2
    Output: 1
    Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

    Example 2:

    1
    2
    3
    Input: 3
    Output: 2
    Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

    Example 3:

    1
    2
    3
    Input: 4
    Output: 3
    Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
  • 提示

    0 ≤ N ≤ 30

解题思路

思路一

使用递归方法。

代码提交

Python,用时20ms,内存11.8M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
cache = {}
def recur_fib(N):
if N in cache:
return cache[N]

if N < 2:
result = N
else:
result = recur_fib(N-1) + recur_fib(N-2)

# put result in cache for later reference.
cache[N] = result
return result

return recur_fib(N)

使用decorator模式做递归方法中的缓存计算。

Python,用时20ms,内存12.1M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from functools import wraps

class Solution(object):
def cache(func):
caches = {}
@wraps(func)
def wrap(*args):
if args not in caches:
caches[args] = func(*args)
return caches[args]
return wrap

@cache
def fib(self, n):
"""
:type N: int
:rtype: int
"""
if n < 2:
return n
return self.fib(n-1) + self.fib(n-2)

进行Recursion探索时完成的,其他解法后续补充。

-------------本文结束感谢您的阅读-------------
0%