【LeetCode】(70)Climbing Stairs (Easy)
2015-08-22 20:24
429 查看
题目
Climbing Stairs
Total Accepted: 65108 TotalSubmissions: 189441My Submissions
Question
Solution
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?
解析
最简单的思路就是用递归,然而这种题目常常递归会出错,超过次数。直观的方法就是迭代,其实也很简单
class Solution { public: int climbStairs(int n) { <span style="white-space:pre"> </span>if (n == 1) <span style="white-space:pre"> </span> return 1; if (n == 2) return 2; vector<int> stNum(n); stNum[0] = 1; stNum[1] = 2; for (int i = 2; i<n; i++) { stNum[i] = stNum[i-1] + stNum[i-2]; } return stNum.back(); } };
不过还是需要使用一个vector的存储空间,可以更有效的降低空间。
class Solution { public: int climbStairs(int n) { <span style="white-space:pre"> </span>if (n == 1) return 1; if (n == 2) return 2; int stNum0 = 1; int stNum1 = 2; int tmp; for (int i = 2;i<n;i++) { tmp = stNum1; stNum1 = stNum0 + stNum1; stNum0 = tmp; } return stNum1; } };
大神提供了一个使用数学公式的方法
class Solution { public: int climbStairs(int n) { <span style="white-space:pre"> </span>const double s = sqrt(5); <span style="white-space:pre"> </span>return floor((pow((1+s)/2, n+1) + pow((1-s)/2, n+1))/s + 0.5); } };
相关文章推荐
- POJ 1995 Raising Modulo Numbers【快速幂】
- CodeForcesGym 100676G Training Camp
- HN OJ 13375 Flowery Trails (spfa的路径遍历)
- Aizu 2302 On or Off
- poj1363——Rails
- 转:CDC,CPaintDC,CClientDC,CWindowDC区别
- (转载)BeginPaint和GetDC有什么区别?
- HDU2141Can you find it? (二分计算计算Ai+Bj+Ck = X)
- HDU 5344(MZL's xor-(ai+aj)的异或和)
- BFS(最短路) HDOJ 4308 Saving Princess claire_
- hdu 3047 Zjnu Stadium(加权并查集)2009 Multi-University Training Contest 14
- 百度地图Baidu LBS 的使用
- POJ 2248 & ZOJ 1937 Addition Chains
- Injection of resource dependencies failed解决办法总结
- int main(int argc,char* argv[])详解
- CaptainGan------ 使用“递归方法”对整个目录进行删除操作
- CaptainGan------使用递归方法实现,向FTP服务器上传整个目录结构、从FTP服务器下载整个目录到本地的功能
- NSLayoutConstraint 布局,配合简单的动画效果
- Robot Framework通过Python SMTP进行email收发测试。
- poj 1995 Raising Modulo Numbers【快速幂】