题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
bool flag = false;
unordered_map<string, int> map = {{"2", 2}, {"3", 3}, {"4", 4}, {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8}, {"9", 9}, {"10", 10}, {"J", 11}, {"Q", 12}, {"K", 13}, {"A", 1}};
string ans;
void dfs(vector<string>& nums, vector<bool>& used, string path, int index,
int sum) {
if (flag) return; //找到一个答案即可
// 终止条件
if (index == 4 ) {
if (sum == 24 ) {
flag = true;
ans = path.substr(1);
}
return ;
}
for (int i = 0; i < 4; i++) {
if (!used[i]) {
used[i] = true;
// 四则运算
dfs(nums, used, path + '+' + nums[i], index + 1, sum + map[nums[i]]);
if (index > 0) {
dfs(nums, used, path + '*' + nums[i], index + 1, sum * map[nums[i]]);
dfs(nums, used, path + '-' + nums[i], index + 1, sum - map[nums[i]]);
dfs(nums, used, path + '/' + nums[i], index + 1, sum / map[nums[i]]);
}
used[i] = false;
}
}
}
int main() {
string s;
while (getline(cin, s)) { // 注意 while 处理多个 case
vector<string> nums;
stringstream ss(s);
string word;
while (getline(ss, word, ' ')) {
if (word.size() > 2) {
cout << "ERROR" << endl; // 存在小王了 需要输入 ERROR
break;
} else {
nums.push_back(word);
}
}
if (nums.size() == 4) {
vector<bool> used(4, false);
dfs(nums, used, "", 0, 0);
// 判断输入结果
if (flag)
cout << ans << endl;
else
cout << "NONE" << endl;
}
}
}
