LeetCode(70)题解: climbing-stairs
2015-08-08 15:07
288 查看
https://leetcode.com/problems/climbing-stairs/
题目:
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?
1)递归: 超时
2)非递归, 避免嵌套调用
递推公式
a_n=a_{n-1}+a_{n-2}.
a_1=1, a_2=2.
问题:给定n求a_n。其实就是斐波那契数列。
AC代码:
题目:
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?
1)递归: 超时
class Solution { public: int climbStairs(int n) { if (n==1) return 1; if(n==2) return 2; return climbStairs(n-1)+climbStairs(n-2); } };
2)非递归, 避免嵌套调用
递推公式
a_n=a_{n-1}+a_{n-2}.
a_1=1, a_2=2.
问题:给定n求a_n。其实就是斐波那契数列。
AC代码:
class Solution { public: int climbStairs(int n) { if (n==1) return 1; if (n==2) return 2; int t=2,x=1,y=2,z; while(t!=n){ t++; z=x+y; x=y; y=z; } return z; } };
相关文章推荐
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- POJ 3007 Organize Your Train part II(枚举)
- uva 529 - Addition Chains
- Snail—1-9这9个数字划分成三个3位数,第一个分别是第二、三个的2倍,3倍
- Spartan6 slave SelectMap configuration fails owing to JTAG?
- JBoss 4.2 MBeans waiting for other MBeans (PersistenceUnit)
- HDU 5358 First One( 2015 Multi-University Training Contest 6)
- fzu 1001 Duplicate Pair
- fzu 1001 Duplicate Pair
- Thai language
- [CareerCup] 4.8 Contain Tree 包含树
- scala学习之:trait的理解
- 算法杂货铺——分类算法之朴素贝叶斯分类(Naive Bayesian classification)
- Duplicate Emails
- hdu 5306 Hiking || 2015 Multi-University Training Contest 6 (优先队列 为小疯子而生)
- U盘无法启动 Ubuntu 的解决方法——基于 UltraISO
- [LeetCode]217-Contains Duplicate 几种解法
- 2015 Multi-University Training Contest 6 Solutions
- POJ 1273 && HDU 1532 Drainage Ditches(最大流-Dinic)
- ORA-09925: Unable to create audit trail file