Python實現N階臺階的走法問題
阿新 • • 發佈:2019-01-10
題目:一棟樓有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