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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 微信上有个女孩子,与我素昧平生,萍水相逢。但有一天,她跟我说,她喜欢我。我内心暗潮涌动,暖意潺潺。 我与她仅有过一...
    蛋蛋oY阅读 659评论 2 3
  • 游泳500米 腹肌
    hdsao阅读 152评论 0 0
  • 因为众所周知的原因,Dropbox不能用了。不开心。幸好Yannis Xu提供了一种方法,可用于获取Dropbox...
    doc001阅读 5,522评论 8 9