24点

这道题,如果是4个数字之间的运算,就有太多种可能了,如果我们能简化到只剩下两个数字,那么两个数字的就只有加减乘除四种运算,只需要计算值是否是24即可,那么怎么把4个数字变成2个数字;
对于4个数,我们只要拿任意的两个数进行加减乘除运算,那么就变成了3个数,再从3个数中间去选两个数进行运算,就变成两个数了;
附上代码
`

include<bits/stdc++.h>

using namespace std;
double a[4];
bool count24(int n)
{
if(n1)
{
if(a[0]
24) return true;
else return false;
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
double c=a[i],d=a[j]; //用一个数组维护 我们把a[i]储存两个数字运算后的值,将最末尾的数赋值给a[j],因为当n-1时候,最后一个数如果不赋值给前面的数,最后一个数就会遍历不到,因为a[j]和a[i]运算后,a[j]的值意见没有用了
a[j]=a[n-1];
a[i]=c+d;
if(count24(n-1)) return true;
a[i]=c*d;
if(count24(n-1)) return true;
a[i]=c-d;
if(count24(n-1)) return true;
a[i]=d-c;
if(count24(n-1)) return true;
if(c!=0)
{
a[i]=d/c;
if(count24(n-1)) return true;
}
if(d!=0)
{
a[i]=c/d;
if(count24(n-1)) return true;
}
a[i]=c;
a[j]=d;
//当上一种情况完成后,要将数组还原
}
}
return false;
}
int main()
{
while(cin>>a[0]>>a[1]>>a[2]>>a[3])
{
if(a[0]0&&a[1]0&&a[2]0&&a[3]0) break;
if(count24(4)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}

`

原文地址:https://www.cnblogs.com/zh1014/p/13745400.html