剑指offer10 斐波那契数列
输入一个整数 n ,求斐波那契数列的第 n 项。
假定从0开始,第0项为0。(n<=39)
样例
输入整数 n=5
返回 5
思路1:
递归的方法,重要的是写明确递归结束的条件,C++代码可以正常通过,python代码溢出
AcWing-21 C++ code:
class Solution {
public:
int Fibonacci(int n) {
if(n == 0 || n == 1){
return n;
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
};
AcWing-21 python code:
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0 or n == 1:
return n
return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
思路2:
&nobsp;&nobsp;&nobsp;&nobsp;用一个数组记录结果,然后依次迭代计算出n的时候的值
&nobsp;&nobsp;&nobsp;&nobsp;时间复杂度和空间复杂度都为O(n)
AcWing-21 C++ code:
class Solution {
public:
int Fibonacci(int n) {
int res[40];
res[0] = 0;
res[1] = 1;
for(int i = 2; i <= n; i++){
res[i] = res[i - 1] + res[i - 2];
}
return res[n];
}
};
AcWing-21 python code:
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
res = []
res.append(0)
res.append(1)
for i in range(2, n+1):
res.append(res[-1] + res[-2])
return res[n]
思路3:
&nobsp;&nobsp;&nobsp;&nobsp; 用三个变量记录,然后依次迭代计算出n的时候的值。
&nobsp;&nobsp;&nobsp;&nobsp;时间复杂度为O(n),空间复杂度为O(1)
AcWing-21 C++ code:
class Solution {
public:
int Fibonacci(int n) {
if(n == 0 || n == 1){
return n;
}
int res_left = 0;
int res_right = 1;
for(int i = 2; i <= n; i++){
res_left = res_left + res_right;
swap(res_left, res_right);
}
return res_right;
}
};
AcWing-21 python code:
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0 or n == 1:
return n
res_left = 0
res_right = 1
for i in range(2, n + 1):
res = res_left + res_right
res_left = res_right
res_right = res
return res