41-Climbing Stairs-leetcode
2016-05-01 12:30
393 查看
Climbing Stairs My Submissions QuestionEditorial Solution
Total Accepted: 106498 Total Submissions: 290003 Difficulty: Easy
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?
思路:so easy
重要的是思路清晰,对于n阶楼梯,可能由n-1阶迈上来的,也可能由n-2阶楼梯迈上来的,记f(n)为迈上n阶楼梯所需的步数记f(n)为迈上n阶楼梯所需的步数f(n)=f(n−1)+f(n−2)f(n)=f(n-1)+f(n-2)f(2)=2,f(1)=1f(2)=2,f(1)=1
就是一斐波纳挈数列,通项和为an=15√((1+5√2)n−(1−5√2)n)a_n=\frac{1}{\sqrt5}((\frac{1+\sqrt5}{2})^n-(\frac{1-\sqrt5}{2})^n)
这里的f(n)=an+1f(n)=a_{n+1}
这里程序有三种实现方式,递归效率最差,自底向上循环其次,最好的是常数级,用公式
Total Accepted: 106498 Total Submissions: 290003 Difficulty: Easy
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?
思路:so easy
重要的是思路清晰,对于n阶楼梯,可能由n-1阶迈上来的,也可能由n-2阶楼梯迈上来的,记f(n)为迈上n阶楼梯所需的步数记f(n)为迈上n阶楼梯所需的步数f(n)=f(n−1)+f(n−2)f(n)=f(n-1)+f(n-2)f(2)=2,f(1)=1f(2)=2,f(1)=1
就是一斐波纳挈数列,通项和为an=15√((1+5√2)n−(1−5√2)n)a_n=\frac{1}{\sqrt5}((\frac{1+\sqrt5}{2})^n-(\frac{1-\sqrt5}{2})^n)
这里的f(n)=an+1f(n)=a_{n+1}
这里程序有三种实现方式,递归效率最差,自底向上循环其次,最好的是常数级,用公式
class Solution { public: int climbStairs(int n) { vector<int> vec(n+1,0); vec[1]=1;vec[2]=2; if(n<=2)return vec ; for(int i=3;i<=n;++i) vec[i]=vec[i-1]+vec[i-2]; return vec ; } };
相关文章推荐
- Leetcode: 70. Climbing Stairs
- 【LeetCode】Contains Duplicate 解题报告
- 谈谈AI
- hdu 1166 敌兵布阵 + Dairy
- 程序定义了多个入口点。使用 /main (指定包含入口点的类型)进行编译
- 尾递归(Tail Recursion)和Continuation
- 最好用的Nema信号模拟器:NemaStudio 1.30.5885 开发者Nema 必备利器, 包括AIS Simulator,GPS Simulator,weather simulator,ra
- Summer Training Team Selection (1) Problem D Hidden Password STL,字符串匹配,简单题
- Summer Training Team Selection (1) Problem F Line Them Up 判断升序降序
- Summer Training Team Selection (1) Problem A ACM Contest Scoring 水题
- Title Four:Rainy
- TempDailyMonitor
- UVa 514 Rails
- MyBaits-快速入门
- Codeforces 667A Pouring Rain 667B Coat of Anticubism
- vc 6.0 中 error LNK2001: unresolved external symbol _main和fatal error LNK1120: 1 unresolved externals
- 免费邮件服务器:MailEnable
- LightOJ - 1236 Pairs Forming LCM 合数分解
- Codeforces Round #349 (Div. 2)-A. Pouring Rain(数学)
- ORA-01501: CREATE DATABASE failed