题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4165
碰到递归题目还是很蒙,感觉无从下手,其实找出递归关系就很简单了。递归题目的代码量往往很小。
看了这位大牛的解析才弄懂得,超详细又简单易懂。http://www.myext.cn/other/a_21926.html
题意:瓶子里共有N片药片,第一次拿出一片吃掉一半后将另一半放回瓶中。之后每次拿出一个药片,如果这个药片是一半的话就直接吃掉,否则就吃掉一半将另一半放回瓶中。每次拿出的如果是半片药片就用H表示,如果是一整片就用W表示。求吃完这些药片一共有几种方案。
递推关系: dp[i][j]=dp[i-1][j+1]+dp[i][j-1];
#include<iostream>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 31;
long long dp[maxn][maxn];
void init()
{
dp[1][0] = 1;
for(int j = 1; j < maxn; j++)
dp[1][j] = j+1;
for(int i = 2; i < maxn; i++)
{
dp[i][0] = dp[i-1][1];
for(int j = 1; j < maxn; j++)
dp[i][j] = dp[i-1][j+1] + dp[i][j-1];
}
}
int main()
{
init();
int n;
while(scanf("%d",&n) == 1 && n)
{
printf("%lld\n",dp[n][0]);
}
return 0;
}