题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
示例1
输入
3
返回值
4
代码:
public class Solution {
public int JumpFloorII(int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < i; j++) {
dp[i] += dp[j];
}
}
return dp[target];
}
}
思路:
公式:F(n) = F(0) + F(1) + F(2)+… + F(n-1)
优化:
F(n) = F(n-1) + F(n-2) + F(n-3)+…+F(2) + F(1)
F(n-1) = F(n-2) + F(n-3) + …+ F(2) + F(1)
F(n) = F(n-1) + F(n-1)
F(n) = 2 * F(n-1)
代码:
public class Solution {
public int JumpFloorII(int target) {
if(target == 0){
return 1;
}
int sum = 1;
for (int i = 0; i < target -1; i++) {
sum *= 2;
}
return sum;
}
}
位运算解法:
public class Solution {
public int JumpFloorII(int target) {
if(target == 0){
return 1;
}
return 1 << target -1;
}
}