LeetCode 题解工作台
生成斐波那契数列
请你编写一个生成器函数,并返回一个可以生成 斐波那契数列 的生成器对象。 斐波那契数列 的递推公式为 X n = X n-1 + X n-2 。 这个数列的前几个数字是 0, 1, 1, 2, 3, 5, 8, 13 。 示例 1: 输入: callCount = 5 输出: [0,1,1,2,3]…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Generate Fibonacci Sequence core interview pattern
答案摘要
function* fibGenerator(): Generator<number, any, number> { let a = 0;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Generate Fibonacci Sequence core interview pattern 题型思路
题目描述
请你编写一个生成器函数,并返回一个可以生成 斐波那契数列 的生成器对象。
斐波那契数列 的递推公式为 Xn = Xn-1 + Xn-2 。
这个数列的前几个数字是 0, 1, 1, 2, 3, 5, 8, 13 。
示例 1:
输入:callCount = 5 输出:[0,1,1,2,3] 解释: const gen = fibGenerator(); gen.next().value; // 0 gen.next().value; // 1 gen.next().value; // 1 gen.next().value; // 2 gen.next().value; // 3
示例 2:
输入:callCount = 0 输出:[] 解释:gen.next() 永远不会被调用,所以什么也不会输出
提示:
0 <= callCount <= 50
解题思路
方法一
function* fibGenerator(): Generator<number, any, number> {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
/**
* const gen = fibGenerator();
* gen.next().value; // 0
* gen.next().value; // 1
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) because each Fibonacci number up to callCount is generated once. Space complexity is O(N) for storing the resulting array, while the generator itself maintains constant extra memory for the last two numbers. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Check if the candidate correctly uses JavaScript generator syntax for lazy evaluation.
- question_mark
Notice if the candidate handles callCount = 0 without producing any output.
- question_mark
Look for proper state management to yield each Fibonacci number sequentially without precomputing the entire sequence.
常见陷阱
外企场景- error
Returning an array instead of a generator breaks the lazy generation pattern.
- error
Incorrectly updating the previous two numbers can produce the wrong Fibonacci sequence.
- error
Not handling callCount = 0 or edge values up to 50 can cause errors or extra iterations.
进阶变体
外企场景- arrow_right_alt
Generate Fibonacci sequence recursively using a generator function.
- arrow_right_alt
Yield only even Fibonacci numbers up to callCount.
- arrow_right_alt
Implement a generator that supports negative Fibonacci indices as well.