LeetCode 题解工作台

第 N 个泰波那契数

泰波那契序列 T n 定义如下: T 0 = 0, T 1 = 1, T 2 = 1, 且在 n >= 0 的条件下 T n+3 = T n + T n+1 + T n+2 给你整数 n ,请返回第 n 个泰波那契数 T n 的值。 示例 1: 输入: n = 4 输出: 4 解释: T_3 = 0…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

根据题目中给出的递推式,我们可以使用动态规划求解。 我们定义三个变量 , , ,分别表示 , , ,初始值分别为 , , 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

泰波那契序列 Tn 定义如下: 

T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

 

示例 1:

输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

示例 2:

输入:n = 25
输出:1389537

 

提示:

  • 0 <= n <= 37
  • 答案保证是一个 32 位整数,即 answer <= 2^31 - 1
lightbulb

解题思路

方法一:动态规划

根据题目中给出的递推式,我们可以使用动态规划求解。

我们定义三个变量 aa, bb, cc,分别表示 Tn3T_{n-3}, Tn2T_{n-2}, Tn1T_{n-1},初始值分别为 00, 11, 11

然后从 nn 减小到 00,每次更新 aa, bb, cc 的值,直到 nn00 时,答案即为 aa

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

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

复杂度分析

指标
时间complexity is O(n) for both iterative and memoized approaches. Space complexity is O(n) for full DP arrays or O(1) for optimized rolling variables. Memoization avoids exponential recursion time, a key failure mode in naive recursion.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can optimize space using only three variables instead of a full array.

  • question_mark

    Expect discussion on the state transition formula Tn+3 = Tn + Tn+1 + Tn+2.

  • question_mark

    Clarify handling of edge cases n = 0, 1, or 2 to ensure correct base initialization.

warning

常见陷阱

外企场景
  • error

    Using naive recursion without memoization leads to exponential time complexity.

  • error

    Failing to handle the initial base cases correctly can produce off-by-one errors.

  • error

    Attempting to optimize prematurely without ensuring the DP state transition is correctly implemented.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the N-th Fibonacci number using a similar state transition DP approach as a simpler case.

  • arrow_right_alt

    Modify the sequence to sum the previous four numbers and compute the N-th value, testing generalization.

  • arrow_right_alt

    Implement a Tribonacci-like sequence starting with custom initial values, maintaining DP state transitions.

help

常见问题

外企场景

第 N 个泰波那契数题解:状态·转移·动态规划 | LeetCode #1137 简单