最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python解决N阶台阶走法问题的方法分析
时间:2018-01-17 编辑:猪哥 来源:一聚教程网
本文实例讲述了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实现嵌套列表去重方法示例
-
下一个: scrapy爬虫实例分享
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27