Problem Description
有一楼梯共M级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第M级,共有多少种走法?
 
Input
输入数据首先包含一个整数N,表示测试实例的个数,然后是N行数据,每行包含一个整数M(1<=M<=40),表示楼梯的级数。
 
Output
对于每个测试实例,请输出不同走法的数量
 
Sample Input
2
2
3
 
Sample Output
1
2

First--------------------accepted

View Code
 1 #include <stdio.h>
 2 int main()
 3 {
 4     int n, m, count, i, j;
 5     int a[45] = {0};
 6     a[1] = 1;
 7     for (i = 1; i <= 40; i++)
 8     {
 9         a[i + 1] += a[i];
10         a[i + 2] += a[i];    
11     }
12     scanf("%d", &n);
13     while (n--)
14     {
15         scanf("%d", &m);
16         printf("%d\n", a[m]);
17     }
18     return 0;
19 }

f(n): the number of ways

f(n + 1) = f(n + 1) + f(n)

f(n + 2) = f(n + 2) + f(n)

it means that the number of ways in n+1 is the number in n plus the own number. The other means the number of ways in n+2 is the number in n plus the own number.

 

 Second---------------accepted

View Code
 1 #include <stdio.h>
 2 int main()
 3 {
 4     int n, m, count, i, j;
 5     int a[45] = {0};
 6     a[1] = 1;
 7     a[2] = 1;
 8     for (i = 3; i <= 40; i++)
 9     {
10         a[i] = a[i - 1] + a[i - 2];
11     }
12     scanf("%d", &n);
13     while (n--)
14     {
15         scanf("%d", &m);
16         printf("%d\n", a[m]);
17     }
18     return 0;
19 }

Maybe it will be more easy to understand.

f(n)=f(n-2)+f(n-1)

 

Third-------------------Time Limit Exceeded

View Code
Because the recursion is waste of time, then it's wrong, but the result is right and simplier.
 
 
 
 
posted on 2012-11-08 10:03  MrMission  阅读(278)  评论(0编辑  收藏  举报