题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
code:
分析:
- f(0) = 1;
- f(1) = 1;
- f(2) = f(2-1) + f(2-2) = f(0) + f(1);
- f(3) = f(3-1) + f(3-2) + f(3-3) = f(0) + f(1) + f(2);
- f(4) = f(4-1) + f(4-2) + f(4-3) + f(4-4) = f(0) + f(1) + f(2) + f(3);
- f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(n-n) = f(n-1) + f(n-1) = 2 * f(n-1);
递归:
public class Solution { public int JumpFloorII(int target) { if (target <= 0) { return 0; } else if (target == 1) { return 1; } else { return 2 * JumpFloorII(target - 1); } } }
动态规划:
public class Solution { public int JumpFloorII(int target) { if (target <= 0) { return 0; } if (target == 1) { return 1; } int x = 1; int y = 2; for (int i = 2; i <= target; i++) { y = 2 * x; x = y; } return y; } }