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]…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Generate Fibonacci Sequence core interview pattern

bolt

答案摘要

function* fibGenerator(): Generator<number, any, number> { let a = 0;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Generate Fibonacci Sequence core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一个生成器函数,并返回一个可以生成 斐波那契数列 的生成器对象。

斐波那契数列 的递推公式为 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
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
 */
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

生成斐波那契数列题解:Generate Fibonacci Sequ… | LeetCode #2648 简单