leetcode | Climbing Stairs
2015-06-23 08:29
489 查看
Climbing Stairs : 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?
解析:
本题是个动态规划问题,最优解可有子问题的的最优解组成,具有重复的子问题。
由题目可知要求到达第n阶台阶的所有方法f(n),又每次能登1~2个台阶,
- 从 n-1 阶登 1 步 到达 n 阶
- 从 n-2 阶登 2 步 到达 n 阶
因此 f(n)=f(n−1)+f(n−2)f(n) = f(n-1) + f(n-2) 费波那也数列
难点在于想到递归式,对于递归问题注意从后往前看。
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阶台阶的所有方法f(n),又每次能登1~2个台阶,
- 从 n-1 阶登 1 步 到达 n 阶
- 从 n-2 阶登 2 步 到达 n 阶
因此 f(n)=f(n−1)+f(n−2)f(n) = f(n-1) + f(n-2) 费波那也数列
难点在于想到递归式,对于递归问题注意从后往前看。
class Solution { public: // f(n) = f(n-1)+f(n-2) int climbStairs(int n) { int prev = 0; int cur = 1; for(int i = 1; i <= n; i++) { int temp = cur; cur += prev; prev = temp; } return cur; } };
相关文章推荐
- uva live 4394 String painter 间隔dp
- Campaignify 众筹集资 WordPress主题
- ApiDemo/FragmentRetainInstance 解析
- 使用UltraISO制作U盘启动盘
- 阅读:AirBag Boosting Smartphone Resistance to Malware Infection
- Failure [INSTALL_FAILED_OLDER_SDK]
- 属性readwrite,readonly,assign,retain,copy,nonatomic
- POJ 1575 && HDU 1039 Easier Done Than Said?(水~)
- 常用raid概述
- onRetainNonConfigurationInstance和getLastNonConfigurationInstance
- grails、Searchable问题:报此错的原因是因为文件缓存空间冲突;
- Grails多数据源
- grails调用存储过程(调用的时候call不能少了那个一对大括号{},少了调用结果不对)
- grails不想用系统生成的字段id可以自己改
- Grails验证与错误打印
- 在Grails中如何使用Class.forName
- Grails小技巧:工作目录
- grails、groovy创建xml
- grails转换base64
- 【BZOJ】【4152】【AMPZZ2014】The Captain