题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
/**
* 循环实现,代码的时间效率更好
*/
public class Solution {
public int JumpFloor(int target) {
int count = 0;
int first = 1;
int second = 2;
if (target == 0) {
return 0;
} else if (target == 1) {
return 1;
} else if (target == 2) {
return 2;
}
int i = 3;
// 循环实现
while (i <= target) {
count = first + second;
first = second;
second = count;
i++;
}
return count;
}
}
/**
* 递归实现,代码较简洁
*/
public class Solution {
public int JumpFloor(int target) {
if(target <= 2) {
return target;
} else {
return JumpFloor(target-1)+JumpFloor(target-2);
}
}
}
题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
/**
* 循环实现,代码的时间效率更好
*/
public class Solution {
public int JumpFloorII(int target) {
if (target == 0) {
return 0;
}
if (target == 1) {
return 1;
}
int count = 1;
int i = 2;
// 循环实现
while (i <= target) {
count = count *2;
i++;
}
return count;
}
}
/**
* 递归实现,代码较简洁
*/
public class Solution {
public int JumpFloorII(int target) {
if(target <= 2) {
return target;
}
else {
return JumpFloorII(target - 1) * 2;
}
}
}