题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
题目分析:
f(0) = 1; 表示n级台阶一次跳n级,只有一种跳法
f(1) = 1;
f(2) = 2;
f(3) = f(2) + f(1)+ f(0)
...
f(n) = f(n-1)+f(n-2)+..+f(n-n)
更简单的做法就是:f(n) = 2*f(n-1),一行代码就可以搞定
Java代码:
public class JumpFloor2 { public static int jumpFloorII(int target) { if (target == 0) return 0; if (target == 1) return 1; if (target == 2) return 2; int[] res = new int[target]; res[0] = 1; res[1] = 2; for (int i = 2; i<target; ++i){ for (int j=0; j<i; ++j) res[i] += res[j]; res[i] += 1; } return res[target-1]; } public static int jumpFloor2(int target){ int a=1; return a<<(target-1); } public static void main(String[] args){ // System.out.println(jumpFloorII(5)); System.out.println(jumpFloor2(5)); } }