备战考研算法笔记(八)N阶楼梯上楼问题

题目描述:

N阶楼梯上楼问题:一次可以走两阶或一阶,问有多少种上楼方式。(要求采用非递归)

输入:

输入包括一个整数N,(1<=N<90)。

输出:

可能有多组测试数据,对于每组数据,
输出当楼梯阶数是N时的上楼方式个数。

样例输入:
4
样例输出:
5

超时代码一枚
#include <stdio.h>

#include <malloc.h>
long long int num=0;
void search(int N)
{
    int temp=N;
  if(N-1>=0)
  {
    N--;
    if(N==0)
    {num++;return;}
    search(N);
    
  }
  N++;
  if(N-2>=0)
  {
      N=N-2;
      if(N==0)
     {num++;return;}
      search(N);
      return;
   }
  else
   return;
}

int main()
{
 int  input;
    while(scanf("%d",&input)!=EOF)
 {
    if(input<90&&input>=0)
     {num=0;
     search(input);
     printf("%lld
",num);
     }
}
    return 0;
}

后来竟然用的是数组,神奇啊!

#include "stdio.h"
#include "stdlib.h"

int main()
{
        int i,N;
        long long a[100];
        while(~scanf("%d",&N))
        {                
                a[0]=0;
                a[1]=1;
                a[2]=2;
                for(i=3;i<100;i++)
                        a[i]=a[i-1]+a[i-2];
                printf("%lld
",a[N]);
        }
        
        return 0;
        
}
但是用java解决问题的那位老兄,用到了排列,我还没想清楚!
原文地址:https://www.cnblogs.com/ligen/p/3283524.html