题目大意:
Problem Description
在一无限大的二维平面中,我们做如下假设:<br>1、 每次只能移动一格;<br>2、 不能向后走(假设你的目的地是“向上”,那么你可以向左走,可以向右走,也可以向上走,但是不可以向下走);<br>3、 走过的格子立即塌陷无法再走第二次;<br><br>求走n步不同的方案数(2种走法只要有一步不一样,即被认为是不同的方案)。<br>
Input
首先给出一个正整数C,表示有C组测试数据<br>接下来的C行,每行包含一个整数n (n<=20),表示要走n步。<br>
Output
请编程输出走n步的不同方案总数;<br>每组的输出占一行。<br>
Sample Input
2 1 2
Sample Output
3 7
解题思路:
f[n]表示走n步,最后一步可能向上,向左或向右,无论倒数第二步怎么走,最后一步都能向上,所以最后一步向上的走法为f[n-1];
当最后一步向左或向右时要考虑第n-1步,如果第n-1步向上(方案为f[n-2])则,第n步向左或向右的方案为2*f[n-2],如果第n-1步不向上(方案为f[n-1]-f[n-2]),则最后一步向左或向右的情况为f[n-1]-f[n-2];
当最后一步向左或向右时要考虑第n-1步,如果第n-1步向上(方案为f[n-2])则,第n步向左或向右的方案为2*f[n-2],如果第n-1步不向上(方案为f[n-1]-f[n-2]),则最后一步向左或向右的情况为f[n-1]-f[n-2];
代码:
#include<iostream> using namespace std; int main() { int n,c; cin>>c; int a[21]; a[0]=0; a[1]=3; a[2]=7; for(int i=3;i<=21;i++) a[i]=a[i-1]*2+a[i-2]; while(c--) { cin>>n; cout<<a[n]<<endl; } return 0; }