跳至主要內容

斐波那契数列


斐波那契数列

题目

写一个函数来计算第n个斐波那契数。 斐波那契数列是一系列数字,其中每个数字是前两个数字的和。最初的几个斐波那契数是:0,1,1,2,3,5,8,数学上我们可以定义斐波那契数为:

Fib(n) = Fib(n-1) + Fib(n-2), 其中:n > 1
给定基准情况: Fib(0) = 0, and Fib(1) = 1

题解

递归

class Fibonacci {

  public int CalculateFibonacci(int n) {
    if(n < 2)
      return n;
    return CalculateFibonacci(n-1) + CalculateFibonacci(n-2);
  }

  public static void main(String[] args) {
    Fibonacci fib = new Fibonacci();
    System.out.println("第5个斐波那契数:---> " + fib.CalculateFibonacci(5));
    System.out.println("第6个斐波那契数:---> " + fib.CalculateFibonacci(6));
    System.out.println("第7个斐波那契数:---> " + fib.CalculateFibonacci(7));
  }
}

自顶向下(备忘录)

class Fibonacci {

  public int CalculateFibonacci(int n) {
    int dp[] = new int[n + 1];
    return CalculateFibonacciRecursive(dp, n);
  }

  public int CalculateFibonacciRecursive(int[] dp, int n) {
    if (n < 2)
      return n;
    if (dp[n] == 0)
      dp[n] = CalculateFibonacciRecursive(dp, n - 1) + CalculateFibonacciRecursive(dp, n - 2);
    return dp[n];
  }

  public static void main(String[] args) {
    Fibonacci fib = new Fibonacci();
    System.out.println("第5个斐波那契数:---> " + fib.CalculateFibonacci(5));
    System.out.println("第6个斐波那契数:---> " + fib.CalculateFibonacci(6));
    System.out.println("第7个斐波那契数:---> " + fib.CalculateFibonacci(7));
  }
}

自底向上

class Fibonacci {

  public int CalculateFibonacci(int n) {
    if (n < 2)
      return n;

    int dp[] = new int[n + 1];
    dp[0] = 0;
    dp[1] = 1;
    for (int i = 2; i <= n; i++)
      dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
  }

  public static void main(String[] args) {
    Fibonacci fib = new Fibonacci();
    System.out.println("5th Fibonacci is ---> " + fib.CalculateFibonacci(5));
    System.out.println("6th Fibonacci is ---> " + fib.CalculateFibonacci(6));
    System.out.println("7th Fibonacci is ---> " + fib.CalculateFibonacci(7));
  }
}
上次编辑于:
贡献者: Neil