Python之青蛙跳台階


一直青蛙可以調1個台階或者一次跳2個台階,一共N個台階,有多少種跳法?

#!/usr/bin/env python
#coding=utf-8

def qingwa(step):
    if step <= 0:
        raise Exception('error')
    if step == 1:
        return 1
    if step == 2:
        return 2
    return qingwa(step - 1) + qingwa(step - 2)
    
def qingwa1(step):
    if step <= 0:
        raise Exception('error')
    if step == 1:
        return 1
    if step == 2:
        return 2
 
    list1 = []
    list1.append(0)
    list1.append(1)
    list1.append(2)
    
    for i in range(3, step + 1):
        list1.append(list1[i - 1] + list1[i - 2])
    return list1[-1]
    
def qingwa2(step):
    if step <= 0:
        raise Exception('error')
    if step == 1:
        return 1
    if step == 2:
        return 2
        
    pre1 = 2 
    pre2 = 1
    value = 0
    
    for i in range(3, step + 1):
        value = pre1 + pre2
        pre2 = pre1
        pre1 = value
        
    return value
        
   


if __name__ == '__main__':
   
    print(qingwa2(9))
    print(qingwa(-1))
    
    
    
    

  


免責聲明!

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



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