跳至主要內容

509. Fibonacci Number


509. Fibonacci Numberopen in new window

🟢   🔖  递归 记忆化搜索 数学 动态规划  🔗 LeetCodeopen in new window

题目

The Fibonacci numbers , commonly denoted F(n) form a sequence, called the Fibonacci sequence , such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1

F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Example 1:

Input: n = 2

Output: 1

Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3

Output: 2

Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4

Output: 3

Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints:

  • 0 <= n <= 30

题目大意

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

F(0) = 0, F(1) = 1

F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

给定 N,计算 F(N)。

提示:0 ≤ N ≤ 30

解题思路

这一题解法很多,大的分类是四种:

  • 递归
  • 记忆化搜索(dp)
  • 矩阵快速幂
  • 通项公式

其中记忆化搜索可以写 3 种方法:

  • 自底向上的
  • 自顶向下的
  • 优化空间复杂度版的

代码

暴力递归法
// 解法一 暴力递归法 时间复杂度 O(2^n),空间复杂度 O(n)
var fib = function (n) {
	if (n <= 1) {
		return n;
	}
	return fib(n - 1) + fib(n - 2);
};

相关题目

相关题目
- [70. 爬楼梯](./0070.md)
- [842. 将数组拆分成斐波那契序列](https://leetcode.com/problems/split-array-into-fibonacci-sequence)
- [873. 最长的斐波那契子序列的长度](https://leetcode.com/problems/length-of-longest-fibonacci-subsequence)
- [1137. 第 N 个泰波那契数](https://leetcode.com/problems/n-th-tribonacci-number)