[Leetcode] Climbing Stairs
2015-10-21 18:49
281 查看
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,每次爬1阶或者2阶层,求爬完台阶的不同的方法数。
第一次爬1阶,则剩下n-1阶;
第一次爬2阶,则剩下n-2阶;
递推表达式为:
F(n) = F(n-1) + F(n-2),F(1) = 1, F(2) = 2;
由于F(n) = F(n-1) + F(n-2) = (F(n-2) + F(n-3)) + (F(n-3) + F(n-4))=.....
由于计算结果没有保存,越往后,重复计算越多,考虑使用动态规划,将F(n-1)和F(n-2) 保存下来。
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
题意:台阶总数为n,每次爬1阶或者2阶层,求爬完台阶的不同的方法数。
第一次爬1阶,则剩下n-1阶;
第一次爬2阶,则剩下n-2阶;
递推表达式为:
F(n) = F(n-1) + F(n-2),F(1) = 1, F(2) = 2;
由于F(n) = F(n-1) + F(n-2) = (F(n-2) + F(n-3)) + (F(n-3) + F(n-4))=.....
由于计算结果没有保存,越往后,重复计算越多,考虑使用动态规划,将F(n-1)和F(n-2) 保存下来。
public class Solution { public int climbStairs(int n) { if (n == 1 || n == 2) { return n; } int pre = 2, beforePre = 1; int curr = 3; for (int i = 3; i <= n; ++i) { curr = pre + beforePre; beforePre = pre; pre = curr; } return curr; } }
相关文章推荐
- saiku-添加数据源以及保证数据源的一致性
- NSSearchPathDirectoriesDomains的理解
- RabbitMQ消息队列(一): Detailed Introduction 详细介绍
- saiku - olap数据源管理
- Jenkins邮件插件的配置(Email Extension Plugin)
- Baidu WIFI Music Box
- vm manager failed to contact configuration server
- 26-main方法不能执行
- aix常用命令(工作自用)
- 利用flashback将DG中failover之后的主库变为备库,不必重新搭建DG
- 使用UltraISO制作ubuntu安装u盘启动盘图文教程
- Changing the IP Address of a Domain Controller
- RFS[18075]: No standby redo logfiles available for thread 1
- 九度考研机试教程 24-题目1436:Repair the Wall
- bnuoj 24251 Counting Pair
- 关于ByteArrayIO和DataIO的用法
- saiku - 访问saiku首页的时候前后台处理流程
- AFNetworkingErrorDomain 错误解决方法
- linker command failed with exit code 1 (use -v to see invocation)
- saiku - 系统登录成功后查询Cubes