一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:想到了高中常用的一种方法–数学归纳法
因为可以跳任意的台阶,所以到第n阶的方法为:
f(n) = f(1)+f(2)+…+f(n-2)+f(n-1);
而f(n-1) = f(1)+f(2)+…+f(n-2)
所以:f(n) = 2f(n-1);
f(1) = 1【到第一阶只有一种方法】
f(2) = 2f(1) = 21 = 2^1
f(3) = 2f(2) = 22*1 = 2^2
…
f(n) = 2^(n-1)
//位运算的效率比公式运算高一些
public class Solution {
public int JumpFloorII(int target) {
return 1 << (target - 1);
//return (int)Math.pow(2,target-1);
}
}