LeetCode-Climbing Stairs(爬楼梯问题)
来源:互联网 发布:linux项目实战 编辑:程序博客网 时间:2024/06/05 22:45
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?
第一反应,递归求解,貌似很简单。但是不幸,超时
public int climbStairs1(int n) { if (n == 1 || n == 2) { return n; } return climbStairs1(n-1) + climbStairs1(n-2); }
为什么超时呢?因为有很多重复的计算,以n=5为例,递归图如下所示:
如果所示,标颜色的需要重复递归调用计算,所以动态规划的思想就是把重叠子问题存储下来,下次调用直接查表即可。比如在第一次递归调用时,n=3已经将结果计算出来,在n=4的时候就不需要就算了,上代码:
public int climbStairs(int n) { if (n == 0 || n == 1 || n == 2) { return n; } int[] r = new int[n+1]; r[1] = 1; r[2] = 2; for (int i = 3; i <= n; i++) { r[i] = r[i-1] + r[i-2]; } return r[n]; }
1 0
- LeetCode-Climbing Stairs(爬楼梯问题)
- LeetCode-Climbing Stairs(爬楼梯问题)
- [LeetCode] Climbing stairs 爬楼梯问题
- LeetCode | Climbing Stairs(爬楼梯)
- LeetCode 70. Climbing Stairs(爬楼梯)
- Climbing Stairs 爬楼梯 @LeetCode
- Leetcode Climbing Stairs 爬楼梯
- LeetCode--Climbing Stairs(爬楼梯)
- LeetCode OJ-70. Climbing Stairs(爬楼梯问题)
- Climbing Stairs(爬楼梯)
- LeetCode OJ 之 Climbing Stairs ( 爬楼梯 )
- [leetcode]Climbing Stairs(爬楼梯 C语言)
- LeetCode-70-Climbing Stairs(爬楼梯)
- Leet Code OJ 70. Climbing Stairs(爬楼梯问题)
- 爬楼梯的问题Climbing Stairs
- 爬楼梯(LintCode Climbing Stairs)
- 70. Climbing Stairs (爬楼梯)
- LintCode Climbing Stairs 爬楼梯
- 程序员常去的14个顶级开发社区
- Matlab并行编程<cellfun & arrayfun>
- codeforces 290div2 C.Fox And Names
- USACO6.2.1 Calf Flac(calfflac)
- 图论——二分图匹配
- LeetCode-Climbing Stairs(爬楼梯问题)
- 最短路径B
- Matlab中巧用LaTex
- matlab乘与点乘的区别 (*与.* ^与.^)
- 谷歌三大核心技术(一)Google File System中文版
- Android手机分辨率基础知识(DPI,DIP计算)
- 最短路径C
- 小Q与百货商店(gift)
- HDU 3342