python遞歸與非遞歸實現斐波那契數列


1.題目描述

大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。

遞歸實現:

class Solution():
    def Fibnacci(self,n):
        if n <= 0:
            return 0
        if n == 1:
            return 1
        return self.Fibnacci(n-1) + self.Fibnacci(n-2)

 非遞歸實現:

def Fibnacci(n):
    result = [0,1]
    if n <= 1:
        return result[n]
    for i in range(2,n+1):
        result.append(result[i-1]+result[i-2])
    return result[n]
2.題目描述 一只青蛙一次可以跳上1級台階,也可以跳上2級。求該青蛙跳上一個n級的台階總共有多少種跳法(先后次序不同算不同的結果)。
[2. Tímù miáoshù yī zhǐ qīngwā yīcì kěyǐ tiào shàng 1 jí táijiē, yě kěyǐ tiào shàng 2 jí. Qiú gāi qīngwā tiào shàng yīgè n jí de táijiē zǒnggòng yǒu duōshǎo zhǒng tiào fǎ (xiānhòu cìxù bùtóng suàn bùtóng de jiéguǒ).]
2. Description of the topic
A frog can jump to the first step or jump to the second level. Ask the frog to jump on an n-level step in total how many kinds of jumps (the order is different).


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM