C 青蛙跳台阶问题
1 问题描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶,求该青蛙跳上一个n级台阶总共有多少种跳法。
2 数学建模:
2.1思路分析
第一级:1种方式,即从0跳到第1级
第二级:2种方式,即从0跳到第1级,从第1级跳到第2级,或者直接从0跳到第2级
第三级:因为青蛙只有两种选择方式。那么跳到第3级的时候只有两种情况,从第1级跳两步到第3级,或者从第2级跳1步到第3级。前面已经计算,到第1级有1种方式,到第2级有2种方式,所以到第3级的方式有:1 * 1+2 * 1=3。每一次从前一级或者前两级到当前级都只有一种方式。
第n级:因此f(n-2)*1+f(n-1)*1=f(n)
2.2 数学公式
3 算法实现
#include <stdio.h>
#include <stdlib.h>
int FabonacciOne(int n)
{
if (n ==-1 )return -1;
if (n == 1) return 1;
if (n == 2) return 2;
if (n > 2)
{
return FabonacciOne(n - 1) + FabonacciOne(n - 2);
}
}
int FabonacciTwo(int n)
{
if (n == -1)return -1;
if (n == 1) return 1;
if (n == 2) return 2;
int a = 1;
int b = 2;
int resultTwo = 0;
for (int i = 3; i <=n; i++)
{
resultTwo = a + b;
a = b;
b = resultTwo;
}
}
int main()
{
int result1 = FabonacciOne(4);
printf("%d\n", result1);
int result2 = FabonacciOne(5);
printf("%d\n", result2);
return 0;
}