题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
看到很多题解包括官方题解都没考虑前后分别括号运算的情况,这里额外写一下
#include <iostream> #include <vector> #include <algorithm> using namespace std; double cal(const double& a, const double& b, const char& c) { if (c == '+') { return a + b; } else if (c == '-') { return a - b; } else if (c == '*') { return a * b; } else return a / b; } bool check24(vector<double>& num) { char op[4] = {'+', '-', '*', '/'}; do { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < 4; ++k) { int first = cal(num[0], num[1], op[i]); int second = cal(first, num[2], op[j]); int secondBracket = cal(num[2], num[3], op[k]); if (cal(second, num[3], op[k]) ==24 || cal(first, secondBracket, op[j]) == 24) return true; } } } } while (next_permutation(num.begin(), num.end())); return false; } int main() { vector<double> num(4); for (int i = 0; i < 4; ++i) { cin >> num[i]; } sort(num.begin(), num.end()); if (check24(num)) { cout << "true" << endl; } else { cout << "false" << endl; } }