leetcode70-Climbing Stairs
2016-03-09 21:33
477 查看
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?
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
/***方法一:采用排列组合(发现当台阶数n增大时,递归结果产生溢出)***/ public class Solution { public long climbStairs(int n) { int count=0; for(int i=0;i<=n/2;i++){ count+=math(n-i)/(math(n-2*i)*math(i)); } return count; } private long math(long j) { if(j==0||j==1) return 1; else return j=j*math(j-1); } /**方法二:同样递归求解,解决了溢出问题,但运出现运行超时(climbStairs(i)重复计算)**/ public int climbStairs(int n){ if (n == 1 || n == 2) { return n; } return climbStairs(n-1) + climbStairs(n-2); } /**方法三:在方法二的基础上做改进,将递归的结果保存至数组中,避免了重复计算的过程**/ if(n==0||n==1||n==2) { return n; } int []cs=new int[n+1]; cs[0]=0; cs[1]=1; cs[2]=2; for(int i=3;i<=n;i++) { cs =cs[n-1]+cs[n-2]; } return cs ; } }在写算法的过程中注意时间复杂度和空间复杂度。节省运行时间和内存占用
相关文章推荐
- WPF中ErrorTemplate导致的空引用at MS.Internal.Controls.TemplatedAdorner.MeasureOverride(Size constraint)
- uva10245 - - The Closest Pair Problem(最近点问题)
- HDU3487 Play with Chain(Splay)
- POJ 1995-Raising Modulo Numbers-整数快速幂
- C++对象作为函数参数 http://blog.csdn.net/tms_li/article/details/7765626
- C++愤恨者札记1——类对象作为函数参数的数据传递过程 http://blog.csdn.net/tms_li/article/details/7765626
- 给出一个有效的算法来确定在整数A1<A2<A3<...<AN的数组中是否存在整数i使得Ai=i
- 1079. Total Sales of Supply Chain (25)
- C++ function、bind以及lamda表达式 http://blog.csdn.net/augusdi/article/details/11771699
- 电商系统Broadleaf文档翻译(六) - 主要实体main entities
- 从马文到AlphaGo AI走过了怎样的70年?
- 解决Windbg的waiting to reconnect
- CodeForces - 630A Again Twenty Five!
- HDU1532----Drainage Ditches
- 人工智能AlphaGo是什么原理
- MAVEN 执行一个main函数的命令
- 630A. Again Twenty Five!
- Async and Await
- Table '.\tablename' is marked as crashed and should be repaired
- 深入分析C++引用 http://blog.csdn.net/webscaler/article/details/6577429