Fibonacci

題目鏈接:Fibonacci

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

f(n) = f(n-1) + f(n-2)
f(1) = 0, f(2) = 1

Recursion Solution:

public int fibonacci(int n) {
    if (n == 1) {
        return 0;
    }
    
    if (n == 2) {
        return 1;
    }
    
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Runtime: exponential, 2^n.
Space: O(n), stack layers

Recursion with memory

passed with 1620 ms

public int fibonacci(int n) {
    if (n == 1) {
        return 0;
    }
    
    if (n == 2) {
        return 1;
    }
    
    int[] mem = new int[n];
    Arrays.fill(mem, -1);
    mem[0] = 0;
    mem[1] = 1;
    
    return fibonacciHelper(n, mem);
}

private int fibonacciHelper(int n, int[] mem) {
    if (mem[n - 1] >= 0) {
        return mem[n - 1];
    }
    
    int res = fibonacciHelper(n - 1, mem) + fibonacciHelper(n - 2, mem);
    mem[n - 1] = res;
    
    return res;
}

Runtime: O(n)
Space: O(n)

DP solution

passed with 1563 ms

public int fibonacci(int n) {
    int first = 0;
    int second = 1;
    if (n == 1) {
        return first;
    }
    if (n == 2) {
        return second;
    }
    int res = 0;
    for (int i = 3; i <= n; i++) {
        res = first + second;
        first = second;
        second = res;
    }
    
    return res;
}

Runtime: O(n)
Space: O(1)

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

相關閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評論 0 10
  • 微信上有個女孩子,與我素昧平生,萍水相逢。但有一天,她跟我說,她喜歡我。我內心暗潮涌動,暖意潺潺。 我與她僅有過一...
    蛋蛋oY閱讀 734評論 2 3
  • 游泳500米 腹肌
    hdsao閱讀 166評論 0 0
  • 因為眾所周知的原因,Dropbox不能用了。不開心。幸好Yannis Xu提供了一種方法,可用于獲取Dropbox...
    doc001閱讀 5,612評論 8 9

友情鏈接更多精彩內容