标签:int 位置 public 斐波那契数列 desc div sub 递归 question
分析:
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; } }
标签:int 位置 public 斐波那契数列 desc div sub 递归 question
原文地址:https://www.cnblogs.com/s-star/p/12512501.html