public class HelloWorld{
public static void main (String args[]){
// 斐波那契数列
// 0 1 1 2 3 5 8 13
// 0 1 2 3 4 5 6
int res = fib(5);
System.out.println(res);
}
// 方法1
public static int fib(int n) {
// n的取值从0开始
// 特殊处理
if (n <= 1) {
return n;
}
// 初始值
int first = 0;
int second = 1;
for (int i=1; i<n; i++) {
int temp = first + second;
first = second;
second = temp;
}
return second;
}
// 方法2
public static int fib(int n) {
if (n == 0 || n == 1) {
return n;
}
return fib(n-2) + fib(n-1);
}
}
原文:https://www.cnblogs.com/gmbjzg/p/14655440.html