判断24点算法,是否有解

先将24点直接转化为浮点型来运算,这样可以省去除0的处理。

本文中是归一思路,4个数求24点--> 3个数求24点-- 2个数求24点-->1个数是不是24点。

bool chk(double a[],int n)

{

if(n == 1)

{

if(fabs(a[0]-24) < 10e-12) {cout << a[0] << endl; return 1;}

else return 0;

}

for(int i = 0; i< n; ++i)

{

for(int j = i+1; j< n; ++j)

{

double t1 = a[i];

double t2 = a[j];

double b[4];

int r = 0;

for(int k = 0; k< n; ++k)

{

if((k != i) && (k != j)) b[r++] = a[k];

}

b[n-2] = t1+t2;

if(chk(b,n-1)) return 1;

b[n-2] = t1*t2;

if(chk(b,n-1)) return 1;

b[n-2] = t1-t2;

if(chk(b,n-1)) return 1;

b[n-2] = t2-t1;

if(chk(b,n-1)) return 1;

b[n-2] = t1/t2;

if(chk(b,n-1)) return 1;

b[n-2] = t2/t1;

if(chk(b,n-1)) return 1;

}

}

return 0;

}

bool chk24(int a, int b ,int c ,int d)

{

double p[4] = {a,b,c,d};

return chk(p,4);

}

作者:Jason Cai
出处:http://www.cnblogs.com/BrainDeveloper/
本文版权归作者(Jason Cai)所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/BrainDeveloper/p/2198486.html