我们先写出前几个阶梯的可能情况
走一层时有一种情况 f(1) =1
走两层时有两种情况 f(2) =2
走三层时有4种情况 f(3) =4
走四层时有7种情况 f(4) =7
我们可以得到一个规律就像斐波那契数列一样的规律
f(1) = f(1)
f(2) = f(1)+f(1)
f(3) = f(1) + f(2) +1
f(4) = f(3) + f(2) + f(1)
f(5) = f(4) + f(3) + f(2)
求解问题就变成了求类似斐波那契的第n个值
两种方法一种for循环 ,一种递归求解
#include<stdio.h>
int main()
{
int f1 = 1;
int f2 = 2;
int f3 = 4;
int count = 0;
for (int i = 4; i <=10; i++)
{
count = f1 + f2 + f3;
f1 = f2;
f2 = f3;
f3 = count;
}
printf("%d",count );
system("pause");
return 0;
}
#include<iostream>
using namespace std;
int count(int n)
{
if (n == 10)
return 1;
else if (n > 10)
return 0;
return count(n + 1) + count(n + 2) + count(n + 3);
}
int main()
{
cout << count(0) << endl;
system("pause");
return 0;
}