题目
一个台阶总共有n级,如果一次可以跳1级、2级、3级。求总共有多少种跳法。
思路
如果整个台阶只有1级,则只有一种跳法;
如果台阶只有2级,则有两种跳法;
如果台阶只有3级,则有四种跳法。
推广到一般情况,记f(n)为n级台阶的跳法。当n>3时,第一次跳1级还是2级还是3级,决定了后面剩下的台阶的跳法数目的不同。如果第一次只跳1级,则剩下的n-1级台阶的跳法数目是f(n-1);如果第一次跳2级,则剩下的n-2级台阶的跳法数目是f(n-2);如果第一次跳3级,则剩下的n-3级台阶的跳法数目是f(n-3)。所以当n>3时,n级台阶的不同跳法的总数为f(n)=f(n-1)+f(n-2)+f(n-3)。
代码
//
// Created by huxijie on 17-3-18.
// 跳台阶
#include <iostream>
using namespace std;
//递归解法
int Steps(int n) {
int result[4] = {0, 1, 2, 4};
if (n <= 3) {
return result[n];
}
return Steps(n - 1) + Steps(n - 2) + Steps(n - 3);
}
//非递归解法
int Steps_2(int n) {
if (n <= 0) {
return 0;
}
int result[4] = {1, 2, 4};
if (n <= 3) {
return result[n - 1];
}
for (int i = 4; i <= n; ++i) {
result[3] = result[0] + result[1] + result[2];
result[0] = result[1];
result[1] = result[2];
result[2] = result[3];
}
return result[3];
}
int main() {
cout<<"Recursive: "<<Steps(10)<<endl;
cout<<"Non Recursive: "<<Steps_2(10)<<endl;
return 0;
}
运行结果
Recursive: 274
Non Recursive: 274
Process finished with exit code 0