跳台阶
题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶共有多少种跳法(先后次序不同算不同的结果)。
思路1:穷举然后找规律。设跳上一个N级台阶共有M种跳法。
N |
M |
1 |
1 |
2 |
2 |
3 |
3 |
4 |
5 |
5 |
8 |
6 |
13 |
发现其实就是斐波那契数列。
思路2:小青蛙跳台阶时,可以有两种方案,一是再跳一级阶梯到达第 i 级阶梯,此时小青蛙处于第 i-1 级阶梯;而是再跳两级阶梯到达第 i 级阶梯,此时小青蛙处于第 i-2 级阶梯。小青蛙跳n层的有f(n)种跳法,跳到n-1层时是分f(n-1)种跳法,跳到n-2层时是f(n-2)种跳法,所以f(n)=f(n-1)+f(n-2)。
方案1:使用递归写斐波那契数列。
class Solution {
public:
int jumpFloor(int number) {
if(number == 0) return 0;
if (number == 1) return 1;
if(number == 2) return 2;
return jumpFloor(number-1)+ jumpFloor(number-2);
}
};
运行时间:658ms
占用内存:504K
方案2:使用循环代替递归。
class Solution {
public:
int jumpFloor(int number) {
int num1 = 1;
int num2 = 1;
int target = number;
int result = 0;
if(target <= 1){
return target;
}
for(int i=1;i<target;i++){
result = num1 + num2;
num1 = num2;
num2 = result;
}
return result;
}
};
运行时间:3ms
占用内存:604K
方案3://该方案目前结果不正确,还在修改中。
class Solution {
public:
int get_c(int low,int high){
int s = 1;
int d = 1;
int count_tmp = high;
int count=0;
while(count < count_tmp){
s = s * low;
d = d * high;
low--;
high--;
count++;
}
return s/d;
}
int jumpFloor(int number) {
int dec = number / 2;
int i = 0;
int result = 0;
int low = number;
int high = 0;
while(i <= dec){
result = result + get_c(low--,high++);
i++;
}
return result;
}
};
参考链接:
https://blog.csdn.net/weixin_38118016/article/details/79068755
https://blog.csdn.net/lskcgh/article/details/80201822
https://blog.csdn.net/qq_34624951/article/details/80099745
变态跳台阶
题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶…它也可以跳上n级,求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路1:穷举法找规律。设跳上N级台阶共有M种跳法。
N |
M |
1 |
1 |
2 |
2 |
3 |
4 |
4 |
8 |
5 |
16 |
其实跳上N级台阶共有跳法
1 + 2^0 + 2^1 + …+ 2^(N-2)种,即M = 2^(N-1)。
方案1:
#include <math.h>
class Solution {
public:
int jumpFloorII(int number) {
if(number == 0) return 0;
if(number == 1) return 1;
int result = 1;
for(int i=0;i<number - 1;i++){
result += pow(2,i);
}
return result;
}
};
运行时间:4ms
占用内存:596K
方案2:
#include <math.h>
class Solution {
public:
int jumpFloorII(int number) {
if(number == 0) return 0;
if(number == 1) return 1;
return pow(2,number-1);
}
};
运行时间:4ms
占用内存:460K
思路2:假设再跳一级阶梯到达第 i 级阶梯,此时小青蛙处于第 i-1 级阶梯;再跳两级阶梯到达第 i 级阶梯,此时小青蛙处于第 i-2 级阶梯…再跳i级阶梯到达第i级阶梯,此时小青蛙处于第0级阶梯;小青蛙跳n层的有f(n)种跳法,跳到n-1层时是f(n-1)种跳法,跳到n-2层时是f(n-2)种跳法…跳到0层时是f(0)种跳法,所以f(n)=f(n-1)+f(n-2) +…+f(0); f(n-1)=f(n-2)+f(n-3) +…+f(0) ,该两式相减可得f(n) = 2*f(n-1)。
方案3:
#include <math.h>
class Solution {
public:
int jumpFloorII(int number) {
if(number == 0) return 0;
if(number == 1) return 1;
if(number == 2) return 2;
return 2*jumpFloorII(number-1);
}
};
运行时间:4ms
占用内存:484K
参考链接:
https://blog.csdn.net/qq_23217629/article/details/51723722