题目描述
给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
输入:
4个1-10的数字。[数字允许重复,但每个数字仅允许使用一次,测试用例保证无异常数字]
输出:
true or false
输入描述:
输入4个int整数
输出描述:
返回能否得到24点,能输出true,不能输出false
示例1
输入
7 2 1 10
输出
true
解题代码:
#include <iostream>
using namespace std;
bool result = false;
// calculate possible result by combine a with b using +-*/
void calculate(double a, double b, double tem[]) {
tem[0] = a + b;
tem[1] = a - b;
tem[2] = a * b;
tem[3] = a / b;
tem[4] = b - a;
tem[5] = b / a;
}
bool check_equal_24(double tem[]) {
bool flag = false;
for (int i = 0; i < 6; i++) {
// in case missing some precision while using division
if (tem[i] > 23.9 && tem[i] < 24.1)
flag = true;
}
return flag;
}
void reduce(double array[], double len) {
if (len == 2) {
double Tem[6];
calculate(array[0], array[1], Tem);
if (check_equal_24(Tem))
result = true;
}
else if (len == 3) {
for (int i = 0; i < 2; i++) {
for (int j = i + 1; j < 3; j++) {
double Tem[6];
calculate(array[i], array[j], Tem);
for (int k = 0; k < 6; k++) {
double newarray[2] = {array[3-i-j], Tem[k]};
reduce(newarray, 2);
}
}
}
}
else if (len == 4) {
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 4; j++) {
double Tem[6];
double newarray[3];
int q = 0;
for (int p = 0; p < 4; p++) {
if (p != i && p != j) {
newarray[q++] = array[p];
}
}
calculate(array[i], array[j], Tem);
for (int k = 0; k < 6; k++) {
newarray[q] = Tem[k];
reduce(newarray, 3);
}
}
}
}
}
int main(){
double num[4];
while (cin >> num[0] >> num[1] >> num[2] >> num[3]) {
result = false;
reduce(num, 4);
if (result)
cout << "true" << endl;
else
cout << "false" << endl;
}
return 0;
}
/*解题思路 其实就是暴力的遍历四个数对于+ - * /的所有可能组合求出最后的结果
暴力策略:
对于 a, b, c, d四个数我们取其中任意两个数进行计算得到结果 e
--> 变成了 三个数 e, c, d, 再n任取两个数进行计算得到结果 f
--> n变成了两个数 f, d, 将该两个数进行计算将结果与 24进行比较,
--> 比较我采用的是 只要结果 (23.9, 24.1)j之间即认为正确, 考虑的是以防在计算过程中出现精度丢失(比如出现 1/3时)
*/