一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法。

 1 /**
 2  * 问题描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共需要多少种跳法。
 3  */
 4 #include <stdio.h>
 5 
 6 // 递归算法
 7 int faci(int n)
 8 {
 9     if (n == 0)
10         return 0;
11     else if (n == 1)
12         return 1;
13     else if (n == 2)
14         return 2;
15     else
16         return faci(n - 1) + faci(n - 2);
17 }
18 
19 // 迭代算法
20 int faci_iter(int n)
21 {
22     if (n == 0)
23         return 0;
24     int a = 1, b = 2, c;
25     for (int i = 1; i < n; i++)
26     {
27         c = a + b;
28         a = b;
29         b = c;
30     }
31     return a;
32 }
33 int main()
34 {
35     // 测试
36     printf("%d\n", faci(10));
37     printf("%d\n", faci_iter(10));
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/sqdtss/p/11167188.html