跳台阶问题
来源:互联网 发布:国际地图导航软件 编辑:程序博客网 时间:2024/06/07 00:40
跳台阶
问题描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:对于第n个台阶来说,只能从n-1或者n-2的台阶跳上来,所以F(n) = F(n-1) + F(n-2),即斐波拉契数序列1、2、3、5……。
/** * @author lanxuewei * 方法1->迭代 * 方法2->递归 * */public class Solution { //方法1->迭代 public int JumpFloor1(int target) { int first = 1; int second = 2; int temp = 0; if(target <= 2){ return target; } else{ for(int i = 3; i <= target; i++){ temp = first + second; first = second; second = temp; } } return second; } //方法2->递归 public int JumpFloor2(int target) { if (target <= 0) { return 0; } else if (target == 1) { return 1; } else if (target ==2) { return 2; } else { return JumpFloor2(target-1) + JumpFloor2(target-2); } } public static void main(String[] args) { //测试 Solution test = new Solution(); System.out.println("result1 = " + test.JumpFloor1(5)); System.out.println("result2 = " + test.JumpFloor2(5)); }}
不过以本人愚见,这题使用迭代即可,使用递归反而多增加开销罢了。
变态跳台阶
问题描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
直接贴代码:
package test;public class Solution { /** * n级台阶,第一步有n种跳法:跳1级、跳2级...跳n级 * 跳1级,剩下n-1级,则剩下跳法是f(n-1) * 跳2级,剩下n-2级,则剩下跳法是f(n-2) * ... * 易得f(n)=f(n-1)+f(n-2)+...+f(1) * 当n = n-1时,有f(n-1)=f(n-2)+f(n-3)+...+f(1) * 由上两式得 f(n)=2*f(n-1) * @param target * @return result */ public int JumpFloorII(int target) { if (target <= 0){ return -1; } else if (target == 1){ return 1; } else{ return 2 * JumpFloorII(target-1); } } public static void main(String[] args){ //测试 Solution test = new Solution(); int result = test.JumpFloorII(5); System.out.println("result = " + result); }}
首先得到公式:f(n)=2*f(n-1),然后直接使用递归即可。
阅读全文
1 0
- 跳台阶问题(变态跳台阶)
- 跳台阶问题(变态跳台阶)
- 跳台阶与变态跳台阶问题
- 青蛙跳台阶,变态跳台阶问题
- 跳台阶问题(变态跳台阶)
- 跳台阶问题(变态跳台阶)
- 跳台阶以及变态跳台阶问题
- 青蛙跳台阶/变态跳台阶问题
- 跳台阶问题--总结
- 27.跳台阶问题
- 青蛙跳台阶问题
- 27、跳台阶问题
- 跳台阶问题
- 跳台阶问题
- 27.跳台阶问题
- 跳台阶问题
- 跳台阶问题
- 跳台阶问题
- HDU 6060 minimal Steiner Tree 求贡献值
- JDBC和ibatis中时间类型的处理
- Git 和 SVN 之间的区别
- windows xp 不能load "System.Data.SQLite.dll"
- 自定义ro.build.fingerprint
- 跳台阶问题
- 功能齐全的实用 Android 视频播放器
- BZOJ 3524: [Poi2014]Couriers 主席树题解
- final总结
- svm支持向量机
- layui type2 通过url给iframe子页面传值
- HDU6061 RXD and functions[NTT]
- svn: Can't convert string from 'UTF-8' to native encoding
- redis-sentinels 启动报错:All sentinels down, cannot determine where is redis-sentinel master is running.