20.Climbing Stairs
2015-10-18 10:35
423 查看
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?
分析:f(n)=f(n-1)+f(n-2)。
方法一:看到这题目之后第一反应是用递归的方法做。
但是提交方法一之后,运行超时。继续分析发现,可以采用动态规划的思想做,用数组保存f[1..n]的值。
方法三:方法二中已经极大的提高了计算效率,但是保存一个数组是没有必要的,只需要保存三个值就好了。计算第i个只需要知道i-1和i-2对应的值就好了。
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
分析:f(n)=f(n-1)+f(n-2)。
方法一:看到这题目之后第一反应是用递归的方法做。
/** * 递归的思想做f(n)=f(n-1)+f(n-2),理论对,但是超时。 */ public int climbStairs(int n) { if (n == 0 || n == 1) { return 1; } else if (n == 2) { return 2; } else { return climbStairs(n - 1) + climbStairs(n - 2); } }方法二:递归的思想做。
但是提交方法一之后,运行超时。继续分析发现,可以采用动态规划的思想做,用数组保存f[1..n]的值。
/** * 动态规划的思想:用s[i]记录阶梯有i+1层时走的方法,避免重复计算。使用递归重复计算的话很容易时间超时,所以采用动态规划的思想做。 * 对数组s来说,当求s[i]的时候其之前元素都已知。所以只需要s[i]=s[i-1]+s[i-2]即可。 */ public int climbStairs2(int n) { if (n == 0 || n == 1) { return 1; } else if (n == 2) { return 2; } else { int s[] = new int ; s[0] = 1; s[1] = 2; for (int i = 2; i < n; i++) { s[i] = s[i - 1] + s[i - 2]; } return s[n - 1]; } }
方法三:方法二中已经极大的提高了计算效率,但是保存一个数组是没有必要的,只需要保存三个值就好了。计算第i个只需要知道i-1和i-2对应的值就好了。
/** * 调整方法2中的数组表示的方法,只用三个值来表示,f3 = f1 + f2。 * f1表示比f3差两个台阶的可上方法数量,f2表示比f3差一个台阶的可上方法数。 */ public int climbStairs3(int n) { if (n == 0 || n == 1) { return 1; } else { int f1 = 1; int f2 = 1; int f3 = 0; for (int i = 2; i <= n; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; } return f3; } }
相关文章推荐
- HDU 4770 Lights Against Dudely(二进制枚举子集)
- Error:Execution failed for task ':asynctask:packageDebug'
- UVa1326--Jurassic Remains(折半搜索)
- RAID基础知识总结
- iframe与主框架跨域相互访问方法
- Outlook 2013 重新联姻Hotmail ,Exchange ActiveSync牵线搭桥
- Django使用email进行身份验证
- Brain的同步规则
- 解决:打开OleView报错 dllregisterserver in iviewers failed
- C++中智能指针的设计和使用 http://blog.csdn.net/hackbuteer1/article/details/7561235
- 解决os x el capitan proxychains 不能用 (关闭SIP)
- <LeetCode><Easy> 70 Climbing Stairs #斐波那契数列
- mesos-go/examples/zkdetect/main.go 测试
- 开启ubuntu默认root的权限(su: Authentication failure)
- 关于调用gethostbyname失败的原因:Host name lookup failure.
- 在盒子里思考——11位人工智能科学家的探索与发现的笔记
- LeetCode OJ:Contains Duplicate III(是否包含重复)
- available()在不同的地方使用,结果不同
- 异常安全,RAII与C++11 http://www.cnblogs.com/mavaL/articles/2515381.html
- 【C++设计技巧】C++中的RAII机制 http://www.cnblogs.com/gnuhpc/archive/2012/12/04/2802307.html