366. 斐波納契數(shù)列

描述

查找斐波納契數(shù)列中第 N 個(gè)數(shù)。
所謂的斐波納契數(shù)列是指:
前2個(gè)數(shù)是 0 和 1 。
第 i 個(gè)數(shù)是第 i-1 個(gè)數(shù)和第i-2 個(gè)數(shù)的和。
斐波納契數(shù)列的前10個(gè)數(shù)字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

注意事項(xiàng)

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

樣例

給定 1,返回 0
給定 2,返回 1
給定 10,返回 34

代碼

  1. 迭代法: 時(shí)間復(fù)雜度O(n)空間復(fù)雜度O(1)
public class Solution {
    /*
     * @param n: an integer
     * @return: an ineger f(n)
     */
    public int fibonacci(int n) {
        int a = 0;
        int b = 1;
        // 關(guān)于i < n - 1用 n 等于1, 2, 3捋一下就可確定
        // n = 1 for循環(huán)迭代零次,直接返回a
        // n = 2 for循環(huán)迭代一次,b 的值賦給a,返回a
        // n = 3 for循環(huán)迭代兩次,第一次迭代 c 的值賦給b,第二次迭代b的值賦給a,返回a
        // 寫法怎么寫都行,重要的是把對(duì)應(yīng)的值返回
        for (int i = 0; i < n - 1; i++) {
            int c = a + b;
            a = b; 
            b = c;
        }
        return a;
    }
}
  1. 遞歸: 時(shí)間復(fù)雜度O(2 ^ n),空間復(fù)雜度為O(2 ^ n)
public class Solution {
    /*
     * @param n: an integer
     * @return: an ineger f(n)
     */
    public int fibonacci(int n) {
        if (n <= 2) {
            return n - 1;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
}

遞歸做法一般會(huì)超時(shí)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容