Climbing Stairs
2016-04-07 08:15
507 查看
Number of 1 Bits
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?
思路
climb(n) = climb(n-1)+climb(n-2)But
如果你写出这样的代码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); } };
结果是,超时!!!!
这是斐波拉契数列,n-1可以用到n-2的值,不需要重复计算
代码
class Solution { public: int climbStairs(int n) { if(n==0||n==1||n==2) return n; /* 用数组 int res ; res[1]=1; res[2]=2; for(int i= 3;i<=n;i++) res[i]= res[i-2]+res[i-1]; return res ; */ int a =1,b=2,res; for(int i = 3;i<=n;i++) { res = a+b; a=b; b=res; } return res; } };
相关文章推荐
- [LeetCode] Duplicate Emails 重复的邮箱
- liunx 下scp出现 Permission denied, please try again 的解决办法
- Nexus启动失败处理:The nexus service was launched, but failed to start.
- AIDL实例浅析
- Airtable(数据管理)
- could not bind to address 0.0.0.0:443 no listening sockets available, shutting d
- Mesos 维护原语 (Maintenance Primitives)
- LeetCode *** 70. Climbing Stairs
- 【一天一道LeetCode】#11Container With Most Water
- 【一天一道LeetCode】#11Container With Most Water
- 训练集(train set) 验证集(validation set) 测试集(test set)
- Count ways to reach the n’th stair
- Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-2.xml, reason: Connect
- leetcode——70——Climbing Stairs
- 最简实例说明WAIT、NOTIFY、NOTIFYALL的使用方法
- HDOJ 1789-Doing Homework again【贪心】
- RAII&智能指针
- POJ-1273-Drainage Ditches(最大流)dinic实现 后续模板待补充
- Mastering Bitcoin(掌握比特币)读书笔记
- RabbitMQ消息队列(一): Detailed Introduction 详细介绍