HDU2041 超級樓梯【dp入門】

 HDU2041 超級樓梯

Problem Description

有一樓梯共M級,剛開始時你在第一級,若每次只能跨上一級或二級,要走上第M級,共有多少種走法?

 

 

Input

輸入數據首先包含一個整數N,表示測試實例的個數,然後是N行數據,每行包含一個整數M(1<=M<=40),表示樓梯的級數。

 

 

Output

對於每個測試實例,請輸出不同走法的數量

 

 

Sample Input

2

2

3

 

 

Sample Output

1

2

 

 

Author

lcy

 

 

分析:簡單的dp,到第m階樓梯的方法就是跨一階或者兩階,因爲m階樓梯方法即爲前一種 和前前一種方法之和

//簡單dp
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int dp[41];//只需要一維數組即可,此樓梯種數爲前一個樓梯種數加  前前種數
int main ()
{
        int t,i,n;
        scanf("%d",&t);
        while(t--)
        {
                scanf("%d",&n);
                dp[1]=1;
                dp[2]=1;
                for(i=3;i<=n;i++)
                {
                        dp[i]=dp[i-1]+dp[i-2];
                }
                printf("%d\n",dp[n]);
        }
        return 0;
}
//遞歸法
#include<iostream>
#include<string.h> 
using namespace std;
int f(int a)
{
	if(a<4)
	return a-1;
	if(a>=4)
	return f(a-1)+f(a-2);
}
int main()
{
	int n,m;
	cin>>n;
	while(n--)
	{
		cin>>m;
		cout<<f(m)<<endl;
	}
	return 0;
}

 

發佈了95 篇原創文章 · 獲贊 16 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章