Python解決N階台階走法問題的方法

來源:互聯網
上載者:User
這篇文章主要介紹了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


好的,以上就是分別用了遞迴和遞推法實現的過程。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.