题解 | #24点运算#

24点运算

http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;

//int ADD = 0, SUB = 1, MUL = 2, DIV = 3;
vector<char> Op = {'+', '-', '*', '/'};

unordered_map<string, int> _stoi = {
    {"A", 1},
    {"2", 2},
    {"3", 3},
    {"4", 4},
    {"5", 5},
    {"6", 6},
    {"7", 7},
    {"8", 8},
    {"9", 9},
    {"10", 10},
    {"J", 11},
    {"Q", 12},
    {"K", 13}
};
unordered_map<int, string> _itos = {
    {1, "A"},
    {2, "2"},
    {3, "3"},
    {4, "4"},
    {5, "5"},
    {6, "6"},
    {7, "7"},
    {8, "8"},
    {9, "9"},
    {10, "10"},
    {11, "J"},
    {12, "Q"},
    {13, "K"}
};

vector<int> nums(4);

int calculate(int a, int b, int cal){
    switch(cal){
        case 0:
            return a + b;
            break;
        case 1:
            return a - b;
            break;
        case 2:
            return a * b;
            break;
        case 3:
            return a / b;
            break;
        default:
            return 0;
            break;
    }
}

bool dfs(int start, int sum, vector<int>& ops){
    sum = calculate(sum, nums[start], *(ops.end() - 1)); //
    
    if(start == 3 && sum == 24){
        return true;
    }
    else if(start == 3){
        return false;
    }
    
    //递归
    for(int i = 0; i < 4; i++){
        ops.push_back(i);
        if(dfs(start + 1, sum, ops)){
            return true;
        }
        ops.pop_back();//回溯
    }
    
    return false;
}

int main(){
    vector<string> str(4);
    cin >> str[0] >> str[1] >> str[2] >> str[3];
    
    for(int i = 0; i < 4; i++){
        if(str[i] == "joker" || str[i] == "JOKER"){
            cout<<"ERROR"<<endl;
            return 0;
        }
        nums[i] = _stoi[str[i]];
    }
    
    sort(nums.begin(), nums.end());
    do{
        vector<int> ops; //运算符号 数组
        for(int i = 0; i < 4; i++){
            ops.push_back(i);
            
            if(dfs(1, nums[0], ops)){ //start从1开始
                cout<< _itos[nums[0]]<<Op[ops[0]]
                    << _itos[nums[1]]<<Op[ops[1]]
                    << _itos[nums[2]]<<Op[ops[2]]
                    << _itos[nums[3]]<<endl;
                return 0;
            }
            
            ops.pop_back();//回溯
        }
    }while(next_permutation(nums.begin(), nums.end())); //nums的全排列
    
    cout << "NONE" << endl;
    return 0;
}
华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务