更多2019年的技术文章,欢迎关注我的微信公众号:码不停蹄的小鼠松(微信号:busy_squirrel),也可扫下方二维码关注获取最新文章哦~
T:
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
constraints:
时间限制:1秒空间限制:32768K
本题有两种解决策略:
1、首先能发现的是一个斐波那契的递推公式,也就是f(n) = f(n-1) + f(n-2),因此很容易想到用递归去做,但是这种方式,抽象来看,是自上而下的递归,效率并不高,原因在于其重复计算严重;
2、第二,将递归反其道而行之,采用自下而上的方式(既可以说是递归形式的另一种表达,也可以说是动态规划的简单应用),类似于盖楼房的方式:
递归方式:
/**
* 递归方式解决,其实是一个菲波那切数列,自上而下的方式用递归实现
* @param target
* @return
*/
public int JumpFloor(int target) {
// 两个终止条件
if (target == 1) {
return 1;
} else if (target == 2) {
return 2;
} else {
return JumpFloor(target-1) + JumpFloor(target - 2);
}
}
非递归方式:
/**
* 用动态规划的方式解决,自下而上的方式,避免重复计算的问题
* @param target
* @return
*/
public int JumpStairs(int target) {
int count = 0;
if (target == 1 || target == 2) {
return target;
}
int i = 2;
int preCount1 = 1;
int preCount2 = 2;
while (i < target) {
count = preCount1 + preCount2;
preCount1 = preCount2;
preCount2 = count;
i ++;
}
return count;
}
更多2019年的技术文章,欢迎关注我的微信公众号:码不停蹄的小鼠松(微信号:busy_squirrel),也可扫下方二维码关注获取最新文章哦~