返回介绍

Fibonacci

发布于 2025-02-22 13:01:26 字数 1871 浏览 0 评论 0 收藏 0

Source

Problem

Find the _N_th number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

  • The first two numbers are 0 and 1.
  • The i th number is the sum of i-1 th number and i-2 th number.

The first ten numbers in Fibonacci sequence is:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Example

Given 1 , return 0

Given 2 , return 1

Given 10 , return 34

Note

The _N_th fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

题解

斐波那契数列使用递归极其容易实现,其实使用非递归的方法也很容易,不断向前滚动即可。

C++

class Solution{
public:
  /**
   * @param n: an integer
   * @return an integer f(n)
   */
  int fibonacci(int n) {
    if (n <= 0) return -1;
    if (n == 1) return 0;
    if (n == 2) return 1;

    int fn = 0, fn1 = 0, fn2 = 1;
    for (int i = 3; i <= n; i++) {
      fn = fn1 + fn2;
      fn1 = fn2;
      fn2 = fn;
    }
    return fn;
  }
};

Java

class Solution {
  /**
   * @param n: an integer
   * @return an integer f(n)
   */
  public int fibonacci(int n) {
    if (n <= 0) return -1;
    if (n == 1) return 0;
    if (n == 2) return 1;

    int fn = 0, fn1 = 1, fn2 = 0;
    for (int i = 3; i <= n; i++) {
      fn = fn1 + fn2;
      fn2 = fn1;
      fn1 = fn;
    }

    return fn;
  }
}

源码分析

  1. corner cases
  2. 初始化 fn, fn1, fn2, 建立地推关系。
  3. 注意 fn, fn2, fn1 的递推顺序。

复杂度分析

遍历一次,时间复杂度为 O(n)O(n)O(n), 使用了两个额外变量,空间复杂度为 O(1)O(1)O(1).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文