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…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 状态·转移·动态规划
答案摘要
根据题目中给出的递推式,我们可以使用动态规划求解。 我们定义三个变量 , , ,分别表示 , , ,初始值分别为 , , 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
泰波那契序列 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。
解题思路
方法一:动态规划
根据题目中给出的递推式,我们可以使用动态规划求解。
我们定义三个变量 , , ,分别表示 , , ,初始值分别为 , , 。
然后从 减小到 ,每次更新 , , 的值,直到 为 时,答案即为 。
时间复杂度 ,空间复杂度 。其中 为给定的整数。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.