LeetCode - Climbing Stairs
2013-12-22 04:16
357 查看
Climbing Stairs
2013.12.22 04:13
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?
Solution:
Search for "Fibonacci sequence" and calculate the nth element in the sequence.
Time complexity is O(n), space complexity is O(1).
Accepted code:
2013.12.22 04:13
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?
Solution:
Search for "Fibonacci sequence" and calculate the nth element in the sequence.
Time complexity is O(n), space complexity is O(1).
Accepted code:
class Solution { public: int climbStairs(int n) { // Note: The Solution object is instantiated only once and is reused by each test case. int f1, f2, f3; f1 = 0; f2 = 1; if(n <= 0){ return 0; } for(int i = 0; i < n; ++i){ f3 = f1 + f2; f1 = f2; f2 = f3; } return f3; } };
相关文章推荐
- 在响应链中使用视图控制器Using View Controllers in the Responder Chain[苹果官方文档的翻译]
- HDOJ 1039 Easier Done Than Said?
- 【九度】题目1326:Waiting in Line
- 设计模式(20) - Chain of Responsibility职责链模式
- Winodws Phone 用户赠送额外Skydrive 20G 空间
- 教你10分钟内在Windows上完成Rails开发环境的安装和配置
- Data alignment: Straighten up and fly right
- uva 1450 - Airport(二分)
- python smtp send mail
- 深度学习:又一次推动AI梦想
- uva 1450 - Airport(贪心+二分)
- HDU - 2476 String painter
- 第三次训练——Cube painting
- main原型和参数含义,第三个参数
- ZOJ 3675 Trim the Nails(bfs+状态压缩搜索)
- 手机页面的转换 通过setContentView设置页面布局main.xml 跳转
- Scala中的语言特性是如何实现的(3) -- Trait
- Scala中的语言特性是如何实现的(3) -- Trait
- Delphi 完全时尚手册之 Visual Style 篇 (界面不错) 转自http://blog.csdn.net/iseekcode/article/details/4733229
- Why the “MAVEN2_CLASSPATH_CONTAINER will not be exported or published”