问题描述
求Fibonacci数列的第n项。Fibonacci数列为1,1,2,3,5,...
解决思路
(1) 递归,指数级时间复杂度;
(2) 循环,O(n)时间复杂度;
(3) 矩阵乘法,O(logn)时间复杂度;
(4) 公式法,O(1)时间复杂度。
程序
public class Fibonacci {
public int getNthElemRec(int n) {
if (n <= 0) {
return -1;
}
if (n <= 2) {
return 1;
}
return getNthElemRec(n - 1) + getNthElemRec(n - 2);
}
public int getNthElemNoRec(int n) {
if (n <= 0) {
return -1;
}
if (n <= 2) {
return 1;
}
int a = 1, b = 1;
int res = 0;
while (n >= 3) {
res = a + b;
a = b;
b = res;
--n;
}
return res;
}
}