【LeetCode】70. Climbing Stairs
2015-08-31 10:04
465 查看
题目:
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,则step(n) = step(n-1) + step(n-2)。因为对于n-1的情况,只能是再上一阶台阶成为n,而对于n-2的情况,如果走一步,那么久和n-1一样了,因此若要不同就只能走2步直接变成n。
代码:
class Solution { public: int climbStairs(int n) { if (n <= 2) return n; int step = 3, s1 = 1, s2 = 2, tmp; while (step <= n) { tmp = s1 + s2; s1 = s2; s2 = tmp; ++step; } return s2; } };
递归法(在LeetCode上会超时,应该是堆栈大小太大了):
class Solution { public: int climbStairs(int n) { if(n <= 2) return n; return climbStairs(n-1) + climbStairs(n-2); } };
相关文章推荐
- [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)错误原因
- Linux线程-互斥锁pthread_mutex_t http://blog.csdn.net/zmxiangde_88/article/details/7998458
- 减少页面回流与重绘(Reflow & Repaint)
- foxmail邮箱 邮件地址信息 以及邮件内容信息的导入导出
- XML 元素 http://blog.csdn.net/chaiyu2002/article/details/5967186
- xml节点和元素的关系 http://blog.csdn.net/chaiyu2002/article/details/5967186
- foxmail邮件太多,需要经常手工清理邮件怎么办
- UVALive - 2197 Paint the Roads(费用流)
- epoll详细工作原理 http://blog.csdn.net/hdutigerkin/article/details/7517390
- xmlInitParser和xmlCleanupParser使用详解 http://blog.csdn.net/hdutigerkin/article/details/7548596
- libxml读取xml文件的其他方法 http://blog.csdn.net/hdutigerkin/article/details/7547014
- libxml的使用(4)--xpath搜索节点树 http://blog.csdn.net/hdutigerkin/article/details/7546912
- libxml的使用(2)--读取节点属性 http://blog.csdn.net/hdutigerkin/article/details/7546907
- libxml的使用(1)--读取xml http://blog.csdn.net/hdutigerkin/article/details/7546899
- Leetcode #217 Contains Duplicate
- HDU 4458 Shoot the Airplane(计算几何 判断点是否在n边形内)
- ResponderChain note
- 【转载】MFC的Main函数跑哪去了
- TurboMail邮件系统与利郎服装集团合作
- OC之非ARC环境下循环retain问题