四个数先从小排序,再全排列(因为全排列的函数需要从小到大先排序)
然后暴力求解
using namespace std;
class Solution {
public:
string is24(string s[4])
{
float num[4],x,y,z;
string X,Y,Z,W;
for(int i=0;i<4;i++)
{
switch(s[i][0])
{
case 'A': num[i] = 1.; break;
case 'K': num[i] = 13.; break;
case 'Q': num[i] = 12.; break;
case 'j': return "ERROR";
case 'J':
if(s[i].length()==1)
{
num[i] = 11.;
break;
}
else
return "ERROR";
case '1':
if(s[i].length()==1)
{
num[i] = 1.;
break;
}
else
{
num[i] = 10.;
break;
}
default :
num[i] =1. + char(s[i][0]) - '1';
}
}
for(int i=0;i<3;i++) for(int j=0;j<3-i;j++) if(num[j]>num[j+1]) swap(num[j],num[j+1]); do { for(int i=0;i<4;i++) { switch(int(num[0])) { case 1: W = "A";break; case 10: W = "10";break; case 11: W = "J";break; case 12: W = "Q";break; case 13: W = "K";break; default: W = '0' + char(num[0]); } x = num[0]; switch(i) { case 0: x += num[1];X = W + '+'; break; case 1: x -= num[1];X = W + '-'; break; case 2: x *= num[1];X = W + '*'; break; case 3: x /= num[1];X = W + '/'; break; } switch(int(num[1])) { case 1: X += "A";break; case 10: X += "10";break; case 11: X += "J";break; case 12: X += "Q";break; case 13: X += "K";break; default: X += '0' + char(num[1]); } for(int j=0;j<4;j++) { switch(j) { case 0: y = x+num[2];Y = X + '+'; break; case 1: y = x-num[2];Y = X + '-'; break; case 2: y = x*num[2];Y = X + '*'; break; case 3: y = x/num[2];Y = X + '/'; break; } switch(int(num[2])) { case 1: Y += "A";break; case 10: Y += "10";break; case 11: Y += "J";break; case 12: Y += "Q";break; case 13: Y += "K";break; default: Y += '0' + char(num[2]); } for(int j=0;j<4;j++) { switch(j) { case 0: z = y+num[3]; Z = Y + '+'; break; case 1: z = y-num[3]; Z = Y + '-'; break; case 2: z = y*num[3]; Z = Y + '*'; break; case 3: z = y/num[3]; Z = Y + '/'; break; } switch(int(num[3])) { case 1: Z += "A";break; case 10: Z += "10";break; case 11: Z += "J";break; case 12: Z += "Q";break; case 13: Z += "K";break; default: Z += '0' + char(num[3]); } //if(int(z)==24) if(z==24) return Z; } } } }while(next_permutation(num,num+4)); return "NONE"; }
};
int main()
{
Solution A;
string s[4];
for(int i=0;i<4;i++)
{
cin>>s[i];
};
cout<<A.is24(s)<<endl;
// system("pause");
return 0;
}