Leetcode:climbing_stairs
来源:互联网 发布:子域名需要备案吗 编辑:程序博客网 时间:2024/06/08 16:35
一、 题目
爬楼梯,一共有n阶,每次可以跨1阶或2阶,则爬到顶部一共有多少种爬法?
二、 分析
设f(n)表示爬n阶楼梯的不同种方法数,为了爬到第n阶处,有两种选择:
1. 从n-1阶前进一步
2. 从n-2阶前进两步
因此有,f(n)=f(n-1)+f(n-2) 这不就是斐波那契数列吗?
故有,
方法1:迭代
方法2:递归
方法3:公式法 F(n)=(1/√5)*{[(1+√5)/2]^n -[(1-√5)/2]^n}
class Solution {public: int climbStairs(int n) { int flag; int stair0=1; int stair1=1; if(n<=0) return 0; if(n==1) return 1; for(int i=2;i<=n;i++) { flag=stair1; stair1=stair0+stair1; stair0=flag; } return stair1; }};公式法:class Solution {public: int climbStairs(int n) { double flag=sqrt(5); return floor((pow((1+flag)/2,n+1)+pow((1-flag)/2,n+1))/flag+0.5); }};
0 0
- Leetcode:climbing_stairs
- leetcode--climbing_stairs
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- HDOJ 1026 Ignatius and the Princess I
- c++中的悬浮指针和野指针 二级指针
- Quartus II9.0 在Win7的安装
- Linux命令行之逗趣无极限
- Codeforce 438D-The Child and Sequence
- Leetcode:climbing_stairs
- Maven实现Web应用集成测试自动化 -- 部署自动化(WebTest Maven Plugin)
- HDOJ 1072 Nightmare
- MTU & MSS 详解记录
- nyoj 228 士兵杀敌(五)【树状数组】
- substring()函数实现
- 求对称子字符串的最大长度
- Spark源码阅读环境搭建(基于Intellij IDEA)
- 堆排序