本文實例講述了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好的,以上就是分別用了遞歸和遞推法實現的過程。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答