一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法。
牛客网AC代码(递归):
class Solution {
public:
int jumpFloor(int number) {
if(number <= 0)
return 0;
else if(number == 1)
return 1;
else if(number == 2)
return 2;
return jumpFloor(number-1) + jumpFloor(number-2);
}
};
非递归:
比较倾向于找规律的解法,f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 5, 可以总结出f(n) = f(n-1) + f(n-2)的规律,但是为什么会出现这样的规律呢?假设现在6个台阶,我们可以从第5跳一步到6,这样的话有多少种方案跳到5就有多少种方案跳到6,另外我们也可以从4跳两步跳到6,跳到4有多少种方案的话,就有多少种方案跳到6,其他的不能从3跳到6什么的啦,所以最后就是f(6) = f(5) + f(4);这样子也很好理解变态跳台阶的问题了。
class Solution {
public:
int jumpFloor(int number) {
if(number <= 0)
return 0;
else if(number == 1)
return 1;
else if(number == 2)
return 2;
int a=1,b=2,c=0;
for(int i=2;i<number;i++){
c = a+b;
a = b;
b = c;
}
return b;
}
};
实现代码如下:
#include<iostream>
using namespace std;
//自下而上的算法,避免重复计算,时间复杂度O(n)
long long Fibonacci(unsigned int n){
if(n <= 0)
return 0;
else if(n == 1)
return 1;
else if(n == 2)
return 2;
int a=1,b=2,c=0;
for(int i=2;i<n;i++){
c = a+b;
a = b;
b = c;
}
return b;
}
int main(){
cout<<Fibonacci(0)<<endl;
cout<<Fibonacci(1)<<endl;
cout<<Fibonacci(2)<<endl;
cout<<Fibonacci(3)<<endl;
cout<<Fibonacci(5)<<endl;
cout<<Fibonacci(10)<<endl;
cout<<Fibonacci(40)<<endl;
cout<<Fibonacci(50)<<endl;//超出最大计算范转
return 0;
}
运行结果如下: