斐波那契
解法1:递归
public int Fibonacci(int n) {
if(n==0)return 0;
if(n==1)return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
}
解法2:循环
public int Fibonacci2(int n){
int [] result = {0,1};
if(n<2){
return result[n];
}
int fibNMinus1 = 1;
int fibNMinus2 = 0;
int fibN = 0;
for(int i=2;i<=n;i++){
fibN = fibNMinus1 + fibNMinus2;
fibNMinus2 = fibNMinus1;
fibNMinus1 = fibN;
}
return fibN;
}
解法3:高阶公式法