LeetCode 题解工作台

斐波那契数

斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,F(1) = 1 F(n) = F(n - 1) + F(n - 2),其中 n > 1 给定 n ,请计算 F(n) 。 示例 1: …

category

4

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 状态·转移·动态规划

bolt

答案摘要

我们定义两个变量 和 ,初始时 $a = 0$, $b = 1$。 接下来,我们进行 次循环,每次循环中,我们将 和 的值分别更新为 和 $a + b$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

给定 n ,请计算 F(n)

 

示例 1:

输入:n = 2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1

示例 2:

输入:n = 3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2

示例 3:

输入:n = 4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3

 

提示:

  • 0 <= n <= 30
lightbulb

解题思路

方法一:递推

我们定义两个变量 aabb,初始时 a=0a = 0, b=1b = 1

接下来,我们进行 nn 次循环,每次循环中,我们将 aabb 的值分别更新为 bba+ba + b

最后,返回 aa 即可。

时间复杂度 O(n)O(n),其中 nn 为题目给定的整数 nn。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
class Solution:
    def fib(self, n: int) -> int:
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a
speed

复杂度分析

指标
时间complexity depends on the approach: naive recursion is O(2^n), memoized recursion and iterative DP are O(n). Space complexity ranges from O(n) for DP array or memoization to O(1) for space-optimized iteration.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect correct handling of base cases F(0) and F(1).

  • question_mark

    Check whether the candidate avoids redundant recursive calls using memoization.

  • question_mark

    Watch for space optimization in iterative solutions for follow-up questions.

warning

常见陷阱

外企场景
  • error

    Naive recursion without memoization causes exponential time complexity and stack overflow for larger n.

  • error

    Incorrectly handling base cases leads to off-by-one errors in sequence values.

  • error

    Using unnecessary extra space when a simple two-variable iteration suffices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute Fibonacci modulo 10^9+7 to test large n handling and modular arithmetic.

  • arrow_right_alt

    Return the first n Fibonacci numbers as an array to test iterative DP comprehension.

  • arrow_right_alt

    Implement a recursive Fibonacci with limited stack depth using tail recursion to explore optimization.

help

常见问题

外企场景

斐波那契数题解:状态·转移·动态规划 | LeetCode #509 简单