LeetCode 70:Climbing Stairs
2015-12-14 12:02
417 查看
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
你正在爬一个有n阶台阶的楼梯。
每一次你只能爬1或2阶,请问你有多少种方法爬到楼顶?
经典的青蛙爬楼梯问题,实质上就是求斐波那契数列的前n项和,关键是一开始我用递归时居然提示我超时。。。没办法只好用了迭代(虽然我觉得递归更好理解)
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
你正在爬一个有n阶台阶的楼梯。
每一次你只能爬1或2阶,请问你有多少种方法爬到楼顶?
经典的青蛙爬楼梯问题,实质上就是求斐波那契数列的前n项和,关键是一开始我用递归时居然提示我超时。。。没办法只好用了迭代(虽然我觉得递归更好理解)
/*class Solution { public: int climbStairs(int n) { if(n==1) return 1; else if (n==2) return 2; else return climbStairs(n-1)+climbStairs(n-2); } }; */ class Solution { public: int climbStairs(int n) { if(n==0) return 0; if(n==1) return 1; if(n==2) return 2; else { int x=0,y=1,z=0,sum=2; for(int i=3;i<=n;i++) { z=x+y; x=y; y=z; sum+=y; } return sum; } } };
相关文章推荐
- ARM basic training
- windows安装rails4.2
- Sporadic IOException: Failed to persist config
- Sporadic IOException: Failed to persist config
- VC6.0 error LNK2001: unresolved external symbol _main解决办法
- 带参数的函数main()
- http://www.microsoft.com/en-pk/download/details.aspx?id=40762
- 'Basic' attribute type should not be a persistence entity/a container
- 4-7 UVA 509 RAID!
- hdu 1532 Drainage Ditches(最大流之Ford-Fulkerson算法)
- Adobe AIR 不能卸载的解决方法
- 怎么区分link和domain
- Daily Scrum 12.13
- pair模板类型
- Daily Scrumming* 2015.12.13(Day 5)
- UVa 442 Matrix Chain Multiplication(矩阵链,模拟栈)
- Determining IP information for eth1... failed; no link present. Check cable? 解决办法
- Determining IP information for eth1... failed; no link present. Check cable? 解决办法
- MINI2440移植xenomai记录
- 机器学习: 朴素贝叶斯(Naive Bayes)