题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
使用枚举法,全排列所有可能顺序,运算符只有64种可能,判断最后结果是否为24即可。注意需要保证除法时要整除得到24才行
#include <algorithm> #include <iostream> #include <vector> using namespace std; double cal(int num1, int num2, char opt) { if (opt == '+') return num1 + num2; else if (opt == '-') return num1 - num2; else if (opt == '*') return num1 * num2; else return (double)num1 / (double)num2; } bool judge(vector<int> nums, char opt[]) { sort(nums.begin(), nums.end()); do { for (int i = 0; i < 4; i ++) { double num_12 = cal(nums[0], nums[1], opt[i]); for (int j = 0; j < 4; j ++) { double num_23 = cal(num_12, nums[2], opt[j]); for (int k = 0; k < 4; k ++) { double num_34 = cal(num_23, nums[3], opt[k]); if (num_34 == 24.0 ) { // cout << "true" << endl; // cout << num_34 << endl; // cout << nums[0] << opt[i] << nums[1] << opt[j] << nums[2] << opt[k] << nums[3]<< endl; return true; } } } } } while (next_permutation(nums.begin(), nums.end())); return false; } int main() { vector<int> nums; for (int i = 0 ; i < 4; i ++) { int num = 0; cin >> num; nums.push_back(num); } char opt[4] = {'+', '-', '*', '/'}; if(judge(nums, opt)) cout << "true" << endl; else cout << "false" << endl; } // 64 位输出请用 printf("%lld")