您的位置:首页 > 其它

递推递归练习C递归的函数

2017-03-31 10:11 190 查看
Description

给定一个函数 f(a, b, c):
如果 a ≤ 0 或 b ≤ 0 或 c ≤ 0 返回值为 1;
如果 a > 20 或 b > 20 或 c > 20 返回值为 f(20, 20, 20);
如果 a < b 并且 b < c 返回 f(a, b, c−1) + f(a, b−1, c−1) − f(a, b−1, c);
其它情况返回 f(a−1, b, c) + f(a−1, b−1, c) + f(a−1, b, c−1) − f(a-1, b-1, c-1)。
看起来简单的一个函数?你能做对吗?

Input

输入包含多组测试数据,对于每组测试数据:
输入只有一行为 3 个整数a, b, c(a, b, c < 30)。

Output

对于每组测试数据,输出函数的计算结果。

Sample Input

1 1 1
2 2 2


Sample Output

2
4
这道题一开始我就照着题目直接翻译,然后上交后发现超时,原来这题目还有一个小坑,需要做一些记忆化搜索,这样才不会超时,我是设置了一个数组,要是已经出现过就不再重复计算,下面是我的ac代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int m[21][21][21];
int f(int a,int b,int c)
{
if(a<=0||b<=0||c<=0)return 1;
else if(a>20||b>20||c>20)return f(20,20,20);
if(m[a][b][c]==0)
{
if(a<b&&b<c)return m[a][b][c]=f(a,b,c-1)+f(a,b-1,c-1)-f(a,b-1,c);
else return m[a][b][c]=f(a-1,b,c)+f(a-1,b-1,c)+f(a-1,b,c-1)-f(a-1,b-1,c-1);
}
else return m[a][b][c];
}
int main()
{
int a,b,c;
memset(m,0,sizeof(m));
while(cin>>a>>b>>c)
{
cout<<f(a,b,c)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: