剑指offer - 斐波那契数列
题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
code:
分析:
- f(0) = 0;
- f(1) = 1;
- f(2) = f(2-1) + f(2-2);
- f(3) = f(3-1) + f(3-2);
- f(n) = f(n-1) + f(n-2) (n>=2,n∈N*)
递归:
public class Solution { public int Fibonacci(int n) { if (n <= 1) { return n; } return Fibonacci(n - 1) + Fibonacci(n - 2); } }
数组存储:
public class Solution { public int Fibonacci(int n) { if (n <= 1) { return n; } int arr[] = new int[n + 1]; arr[0] = 0; arr[1] = 1; for (int i = 2; i <= n; i++) { arr[i] = arr[i - 1] + arr[i - 2]; } return arr[n]; } }
动态规划:
public class Solution { public int Fibonacci(int n) { if (n <= 1) { return n; } //存储n位置值的变量 int x = 1; //存储n-1位置的变量 int y = 0; for (int i = 2; i <= n; i++) { //i位置的值 x = x + y; //i-1位置的值 y = x - y; } //返回n位置值 return x; } }