写了个超级傻的,各种没效率,您别笑话囧
int pl(int a, int b) { return a + b; }
int mi(int a, int b) { return a - b; }
int ti(int a, int b) { return a * b; }
int di(int a, int b) { return (b && !(a % b)) ? (a / b) : -12345 ; }
int (*op[4])(int a, int b) = {&pl, &mi, &ti, &di};
const char *name[4] = {"+", "-", "*", "/"};
char result[128] = {0};
bool tryit(int nums[], char* res)
{
char result[128];
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
for(int k = 0; k < 4; k++)
if ((*op[k])((*op[j])((*op[i])(nums[0], nums[1]), nums[2]), nums[3]) == 24)
{
sprintf(res, "(((%d %s %d) %s %d) %s %d)\0", nums[0], name[i], nums[1],
name[j], nums[2], name[k], nums[3]);
return true;
}
else if ((*op[j])((*op[i])(nums[0], nums[1]), (*op[k])(nums[2], nums[3])) =
= 24) {
sprintf(res, "((%d %s %d) %s (%d %s %d)\0", nums[0], name[i], nums[1],
name[j], nums[2], name[k], nums[3]);
return true;
}
return false;
}
bool twentyFour(int nums[], char* res) {
sort(nums, nums + 4);
do {
if (tryit(nums, res))
return true;
}while(next_permutation(nums, nums + 4));
return false;
}