LeetCode-70-Climbing Stairs
2016-06-24 23:12
393 查看
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?
题意:爬台阶问题。每次能爬一个或两个台阶,问一个有n个台阶的话,一共有几种方法爬到顶端。
思路:
n<=1,此时只有一种。
n>1时,对于每一个台阶i,要到达台阶,最后一步都有两种方法,从i-1迈一步,或从i-2迈两步。
也就是说到达台阶i的方法数=达台阶i-1的方法数+达台阶i-2的方法数。所以该问题是个DP问题。
d(0) = 1
d(1) = 1
d(2) = d(2-1) + d(2-2)
d(3) = d(3-1) + d(3-2)
……
好吧,状态转移方程其实就是Fibonacci数列。
代码实现给出两种方案吧:
python代码如下:
Java代码如下:
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
题意:爬台阶问题。每次能爬一个或两个台阶,问一个有n个台阶的话,一共有几种方法爬到顶端。
思路:
n<=1,此时只有一种。
n>1时,对于每一个台阶i,要到达台阶,最后一步都有两种方法,从i-1迈一步,或从i-2迈两步。
也就是说到达台阶i的方法数=达台阶i-1的方法数+达台阶i-2的方法数。所以该问题是个DP问题。
d(0) = 1
d(1) = 1
d(2) = d(2-1) + d(2-2)
d(3) = d(3-1) + d(3-2)
……
好吧,状态转移方程其实就是Fibonacci数列。
代码实现给出两种方案吧:
python代码如下:
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n<=1: return 1 res = [] res.append(1) res.append(1) for i in range(2,n+1): res.append(res[-1]+res[-2]) return res[-1]
Java代码如下:
public class Solution { public int climbStairs(int n) { if (n<=1) return 1; int oneStep=1,twoStep = 1,res = 0; for (int i = 2; i <= n; i++) { res = oneStep + twoStep; twoStep = oneStep; oneStep = res; } return res; } }
相关文章推荐
- Mybaits的第一个程序
- 谷歌约束控件(ConstraintLayout)扁平化布局入门
- 8.0/9.0 Email 设置
- 磁盘(常见的raid组合)
- 配置mail命令的IMAP和SMTP,接收邮件和发送邮件
- raid卡坏掉,更换同一型号raid卡恢复
- ConstaintLayout的初次使用总结
- 【POJ3411】-Paid Roads 搜索剪枝
- 如何 “解决” WPF中空域问题(Airspace issuse)
- maven install时报错Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile
- Main方法的执行过程(转)
- webkit SDL+Cairo port 移植分享
- 【DSP开发】shared memory VS mailbox
- Repairing a Road
- 【DSP开发】mailbox的使用
- grails调用groovy脚本
- Claims Based Authentication and Token Based Authentication和WIF
- 给DIY的服务器添加raid驱动
- LeetCode 220. Contains Duplicate III
- 编译busybox时使用make menuconfig命令出现下列问题:recipe for target 'scripts/kconfig/lxdialog/checklist.o' failed