Description
在一无限大的二维平面中,我们做如下假设:
1、每次只能移动一格;
2、不能向后走(假设你的目的地是“向上”,那么你可以向左走,可以向右走,也可以向上走,但是不可以向下走);
3、走过的格子立即塌陷无法再走第二次。
求走n步不同的方案数(2种走法只要有一步不一样,即被认为是不同的方案)。
Input
首先给出一个正整数C,表示有C组测试数据。
接下来的C行,每行包含一个整数n(n<=20),表示要走n步。
Output
请编程输出走n步的不同方案总数;
每组的输出占一行。
Sample Input
2
1
2
Sample Output
3
7
解析
这道题有两种解题思路 1.深搜求方案数,但耗时极大
2.数据有规律可循,方案数符合方程 ans[i]=2*ans[i-1]+ans[i-2]
代码一
#include<stdio.h>
#include<string.h>
#define MAX 100
int vis[MAX][MAX],n,ans;
int dir[3][2]={{0,-1},{1,0},{0,1}};
void DFS(int x,int y,int step)
{
if(step==n)
{
ans+=1;
return ;
}
int tempx,tempy;
for(int i=0;i<=2;i++)
{
tempx=x+dir[i][0];
tempy=y+dir[i][1];
if(vis[tempx][tempy]==0)
{
vis[tempx][tempy]=1;
DFS(tempx,tempy,step+1);
vis[tempx][tempy]=0;
}
}
return ;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
memset(vis,0,sizeof(vis));
ans=0;
vis[50][50]=1;
DFS(50,50,0);
printf("%d\n",ans);
}
return 0;
}
代码二
#include<stdio.h>
int ans[30]={1,3};
void solve()
{
for(int i=2;i<=20;i++)
{
ans[i]=2*ans[i-1]+ans[i-2];
}
}
int main()
{
int T;
scanf("%d",&T);
solve();
while(T--)
{
int n;
scanf("%d",&n);
printf("%d\n",ans[n]);
}
return 0;
}