青蛙跳
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解法
public class Solution {
int res = 0;
public int JumpFloor(int target) {
int count = 0;
helper(count, target);
return res;
}
void helper(int count, int target){
if(count == target){
res++;
return;
}
if(count > target) return;
helper(count + 1,target); // helper 的第一个参数不能是 ++count,因为这样的话 count 会自增1,影响后面的 helper 调用
helper(count + 2,target);
}
}
变态青蛙跳台阶
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解法
分析:因为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)
因为f(n-1)=f(n-2)+f(n-3)+…+f(1)
所以f(n)=2*f(n-1)
public class Solution {
public int JumpFloorII(int target)
return 1<<--target;
}
注:上述题目及其部分解法来自牛客网