/**
* Created by 737597978 on 2015/4/13.
* 斐波那契数列第n个数的值
*/
public class Fibonacci {
/**
* 递归实现
*/
public static int getFibo(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return getFibo(n - 1) + getFibo(n - 2);
}
}
/**
*循环实现
*时间复杂度是O(n),空间复杂度是O(1)
*/
public static int getFiboCommon(int n) {
if (n == 1 || n == 2) {
return 1;
}
int pre = 1;
int prepre = 1;
int result = 0;
for (int i = 2; i < n; i++) {
result = pre + prepre;
pre = prepre;
prepre = result;
}
return result;
}
public static void main(String[] args) {
int fibo = Fibonacci.getFibo(10);
System.out.println(fibo);
int fiboCommon=Fibonacci.getFiboCommon(10);
System.out.println(fiboCommon);
}
}