斐波那契数列(Fibonacci sequence)非递归算法:
/**
* 斐波那契数列(Fibonacci sequence), 时间复杂度O(n),空间复杂度 O(n)
* @param n
* @return
*/
private static Integer Fib2(Integer n){
if(n < 1){
return -1;
}
Integer[] a = new Integer[n+1];
a[1] = 1;
a[2] = 1;
for(int i = 3; i<= n ; i++){
a[i] = a[i-1] + a[i-2];
}
return a[n];
}
/**
* 斐波那契数列(Fibonacci sequence), 时间复杂度O(n),空间复杂度 O(1)
* @param n
* @return
*/
private static Integer Fib3(Integer n){
if(n < 1){
return -1;
}
if(n == 1 || n == 2){
return 1;
}
Integer s1 = 1;
Integer s2 = 1;
for(int i=3; i<= n; i++){
// 当前和
s2 = s1 + s2;
// 前一个和
s1 = s2 -s1;
}
return s2;
}