这两道题比较类似,就放到一块来了
这两道题的解题思路我是用的一样的,都是递归求解
当每次只能跳1或2台阶时候,f(n) = f(n-2) + f(n-1),f(1) = 1,f(2) = 2
而当每次可跳1或2或3一直到n台阶时,f(n) = f(n-1) + f(n-2) + ... + 1,同样 f(1) = 1,f(2) =2
下面贴两道题的代码
跳台阶:
public class Solution {
public int JumpFloor(int target) {
if(target == 1 || target == 2){
return target;
}else if(target > 2){
return JumpFloor(target-1) + JumpFloor(target-2);
}else{
return -1;
}
}
}
变态跳台阶:
public class Solution {
public int JumpFloorII(int target) {
/* 这里可以按照上一题的思路来做
* f(n) = f(n-1) + f(n-2) + ... + 1
* f(1) = 1, f(2) = 2
*/
if(target == 1 || target == 2){
return target;
}else if(target > 2){
int sum = 1;
while(target-1 > 0){
sum += JumpFloorII(--target);
}
return sum;
}else{
return -1;
}
}
}
进度 12/66
原文:https://www.cnblogs.com/ihaokun/p/10816444.html