跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解法一:
public class Solution {
public int JumpFloor(int target) { // 递归
if (target == 1) {
return 1;
}
if (target == 2) {
return 2;
}
return JumpFloor(target - 1) + JumpFloor(target - 2);
}
}
解法二:
public class Solution {
public int JumpFloor(int target) { // 非递归
if (target == 1) {
return 1;
}
if (target == 2) {
return 2;
}
int a = 1, b = 2, c = 0;
for (int i = 3; i <= target; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
扩展:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解法一:
public class Solution {
public int JumpFloorII(int target) {
if (target == 1) {
return 1;
}
if (target == 2) {
return 2;
}
int n = 1;
for (int i = 1; i < target; i++) { // 递归
n += JumpFloorII(target - i);
}
return n;
}
public int sum(int[] array, int start, int end) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
}
}
解法二:
public class Solution {
public int JumpFloorII(int target) { // 动态规划
if (target == 1) {
return 1;
}
if (target == 2) {
return 2;
}
int[] array = new int[target];
array[0] = 1;
array[1] = 2;
for (int i = 3; i <= target; i++) {
array[i - 1] = sum(array, 0, i - 1) + 1;
}
return array[target - 1];
}
public int sum(int[] array, int start, int end) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
}
}