码迷,mamicode.com
首页 > 编程语言 > 详细

【算法题1】上台阶问题

时间:2018-04-09 15:50:38      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:strong   str   code   溢出   楼梯   笔试题   end   col   一个   

题目:有一楼梯共m级,刚开始时你在第一级,若每次只能跨上一级或者二级,要走上m级,共有多少走法?注:规定从一级到一级有0种走法。

给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100。为了防止溢出,请返回结果Mod 1000000007的值。

测试样例:
3
返回:2

 

来源:牛客网:京东2016算法工程师笔试题

 1 class goUpstairs:
 2     def countWays(self,n):
 3         if n==1:
 4             return 0
 5         if n==2:
 6             return 1
 7         if n==3:
 8             return 2
 9         else:
10             return (self.countWays(n-1)+self.countWays(n-2)) % 1000000007  # 为了防止溢出
11 
12 
13 class goUpstairs2:
14     def countWays(self,n):
15         res=[1,1]
16         if n==1:
17             return 0
18         while len(res)<n:
19             res.append(res[-1]+res[-2])
20         return res[-1] % 1000000007
21 
22 if __name__=="__main__":
23     # for i in range(1,10):
24     #     print(goUpstairs2().countWays(i))
25     for i in range(1, 10):
26         print(goUpstairs().countWays(i))

本题用递归的斐波那契数列算法会超时,所以可以用方法二。

【算法题1】上台阶问题

标签:strong   str   code   溢出   楼梯   笔试题   end   col   一个   

原文地址:https://www.cnblogs.com/yanmk/p/8760157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!