劍指offer Python版 斐波那契數列

2021-08-18 14:33:23 字數 863 閱讀 4554

大家都知道斐波那契數列,現在要求輸入乙個整數n,請你輸出斐波那契數列的第n項。

n<=39

迴圈。

# -*- coding:utf-8 -*-

class solution:

def fibonacci(self, n):

# write code here

if n <= 2:

return [0, 1, 1][n]

first, second = 1, 1

while n > 2:

first, second = second, first + second

n -= 1

return second

占用記憶體:5728k

遞迴。

# -*- coding:utf-8 -*-

class solution:

def fibonacci(self, n):

# write code here

if n == 0:

return 0

elif n == 1:

return 1

else:

return self.fibonacci(n - 1) + self.fibonacci(n - 2)

不通過

您的**已儲存

執行超時:您的程式未能在規定時間內執行結束,請檢查是否迴圈有錯或演算法複雜度過大。

case通過率為0.00%

顯然,當使用遞迴方法實現時,時間複雜度和空間複雜度都太大。由於函式呼叫自身,而函式呼叫是有時間和空間消耗的:每一次函式呼叫,都需要在記憶體棧中分配空間以儲存引數,返回位址及臨時變數,而且往棧裡壓入資料和彈出資料都需要時間。

斐波那契數列 劍指offer python版

大家都知道斐波那契數列,現在要求輸入乙個整數n,請你輸出斐波那契數列的第n項 從0開始,第0項為0,第1項是1 數列前幾項 0 1 1 2 3 5 8 n 39 示例1輸入 返回值 思路1 遞迴法 思路2 迴圈 遞迴法 coding utf 8 class solution def fibonacc...

劍指offer Python版 替換空格

問題1 替換字串,是在原來的字串上做替換,還是可以重新定義乙個字串做替換 問題2 從前往後替換和從後往前替換一樣嗎?從左往右遍歷元素,若當前元素為空格,則插入 20 並將字串長度增加3.時間複雜度o n n coding utf 8 class solution s 源字串 def replaces...

劍指offer(python版) 2 替換空格

牛客網 leetcode 1 暴力解題 replace直接替換 2 從前向後記錄 數目,從前向後替換 class solution s 源字串 def replacespace self,s write code here 方法一 暴力解題 replace函式替換 s s.replace 20 re...