题解 | #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;
        }
    }
}

全部评论

相关推荐

12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
10-29 21:14
疯犬丨哈士奇:喜欢你的人会主动表白,对你有想法的人会很主动,所以要你的公司不会吊着你所以懂了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务