python剑指offer面试题_剑指offer面试题Q10 斐波那契数列 python解法
Q10.斐波那契數列
題目描述
寫一個函數,輸入n,求斐波那契數列的第n項。
解題思路
思路一
遞歸
遞歸很簡單但是并不能AC
python實現代碼
class Solution:
def Fibonacci(self, n):
# write code here
if n <= 0:
return 0
if n == 1:
return 1
return self.Fibonacci(n-1) + self.Fibonacci(n-2)
思路二
動態規劃
python實現代碼
class Solution:
def Fibonacci(self, n):
# write code here
res = [0]*(n+1)
if n == 0:
return 0
res[0] = 0
res[1] = 1
if n < 2:
return res[n]
for i in range(2, n+1):
res[i] = res[i-1] + res[i-2]
return res[-1]
思路三
循環
python實現代碼
class Solution:
def Fibonacci(self, n):
# write code here
f1 = 0
f2 = 1
if n ==0:
return f1
if n == 1:
return f2
for i in range(2, n+1):
f1, f2 = f2, f1 + f2
return f2
以上
今天開學第一天
2019.0.25
總結
以上是生活随笔為你收集整理的python剑指offer面试题_剑指offer面试题Q10 斐波那契数列 python解法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python三元表达式求值_python
- 下一篇: 数据字典简单例子_Python学习100