#include "iostream"
#include "fstream"
using namespace std;
/*
a(m, n)= n + 1 m = 0
= a(m-1, 1) m>0, n=0
= a(m-1, a(m, n-1)) m>0, n>0
*/
int a[20][20];
int ack(int m, int n)
{
if(m==0)
return n+1;
else if(n==0)
return ack(m-1,1);
else
return ack(m-1,ack(m,n-1));
}
int main()
{
memset(a, 0, sizeof(a));
int m, n;
cout << "输入m:" ;
cin >> m;
cout << "输入n:";
cin >> n;
cout << "ackermann(" << m << "," << n << ")=" << ack(m, n) << endl;
return 0;
}
但以下结果是错误的,也不知为什么
int ack(int m, int n)
{
if(a[m][n] > 0)
return a[m][n];
if(m==0)
return a[m][n] = n+1;
else if(n==0)
return a[m][n] = ack(m-1,1);
else
return a[m][n] = ack(m-1,ack(m,n-1));
}
这样是对的,但失去了备忘录的意义
int ack(int m, int n)
{
if(m==0)
return a[m][n] = n+1;
else if(n==0)
return a[m][n] = ack(m-1,1);
else
return a[m][n] = ack(m-1,ack(m,n-1));
}