剑指Offer_入门_JZZ_斐波那契数列
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。n≤39。
示例1
输入4,返回值3
基本定义
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368
斐波那契数列
特别指出:第0项是0,第1项是第一个1。
这个数列从第3项开始,每一项都等于前两项之和。
解题思路一
public class Solution {
public int Fibonacci(int n){
int temp = 0;
int temp1 = 0;
int temp2 = 1;
int temp3 = 0;
for(int i = 1;i< n;i++){
temp3 = temp1 + temp2;
temp1 = temp2;
temp2 = temp3;
}
if(n > 1 && n <=39){
temp = temp3;
}
if(n == 1){
temp = 1;
}
return temp;
}
}
解题思路二
public class Solution {
public int Fibonacci(int n){
if(n == 0) return 0;
if(n == 1) return 1;
if(n < 0 && n>39) return n;
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
测试
解题思路一:运行时间10ms,内训9636kb
解题思路二:运行时间875ms,内存9696kb
说明
解题思路二用的是递归,显然从外表看是比较完美的,但是这样的内存损耗大,所需时间运行时间多,而解题思路用的是根据斐波那契数列的定义,使用最基本的循环,这样简便。