class Solution {
public:
/*
* @param n: an integer
* @return: an ineger f(n)
*/
int fibonacci(int n) {
// write your code here
if(n == 1)
return 0;
else if(n == 2)
return 1;
int a = 0;
int b = 1;
int sum;
if(n > 2)
{
for(int i = 3; i <= n; i++)
{
sum = a + b;
a = b;
b = sum;
}
}
return sum;
}
};
递归费时间,迭代法可以满足运行时间要求。