這篇文章主要介紹了Python解決N階台階走法問題的方法,簡單描述了走台階問題,並結合執行個體形式分析了Python使用遞迴與遞推演算法解決走台階問題的相關操作技巧,需要的朋友可以參考下
本文執行個體講述了Python解決N階台階走法問題的方法。分享給大家供大家參考,具體如下:
題目:一棟樓有N階樓梯,兔子每次可以跳1、2或3階,問一共有多少種走法?
Afanty的分析:
遇到這種求規律的問題,自己動動手推推就好,1階有幾種走法?2階有幾種走法?3階有幾種走法?4階有幾種走法?5階有幾種走法?
對吧,規律出來了!
易錯點:這不是組合問題,因為第1次走1階、第2次走2階不同於 第1次走2階、第2次走1階
下面是Python的遞迴實現代碼:
def allMethods(stairs): ''''' :param stairs:the numbers of stair :return: ''' if isinstance(stairs,int) and stairs > 0: basic_num = {1:1,2:2,3:4} if stairs in basic_num.keys(): return basic_num[stairs] else: return allMethods(stairs-1) + allMethods(stairs-2) + allMethods(stairs-3) else: print 'the num of stair is wrong' return False
當然也可以用非遞迴的方法來實現,下面就是基於遞推法的代碼:
def allMethod(stairs): '''''遞推實現 :param stairs: the amount of stair :return: ''' if isinstance(stairs,int) and stairs > 0: h1,h2,h3,n = 1,2,4,4 basic_num = {1:1,2:2,3:4} if stairs in basic_num.keys(): return basic_num[stairs] else: while n <= stairs: temp = h1 h1 = h2 h2 = h3 h3 = temp + h1 + h2 return h3 else: print 'the num of stair is wrong' return False
好的,以上就是分別用了遞迴和遞推法實現的過程。