题解 | #24点运算#

24点运算

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

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    const map = {"J":11,"Q":12,"K":13,"A":1};
    const list = (await readline()).split(" ");
    const visited = new Array(4).fill(false);
    let res = "NONE";
    const dfs = (sum,path) => {
        if(visited.filter(item => item).length === 4) {
            if(sum === 24) res = path;
            return sum === 24;
        }
        let flag = false;
        for(let i = 0; i < 4; i++){
            if(!visited[i]){
                visited[i] = true;
                const value = map[list[i]]??(list[i]-0);
                if(path){
                    flag ||= dfs(sum+value,path+"+"+list[i])||dfs(sum-value,path+"-"+list[i])||dfs(sum*value,path+"*"+list[i])||dfs(Math.floor(sum/value),path+"/"+list[i]);
                }else{
                    flag ||= dfs(sum+value,list[i]);

                }
                visited[i] = false;
            }
        }
        return flag;
    }
    if(list.includes("joker") || list.includes("JOKER")){
        res = "ERROR";
    }else{
        // console.log(dfs(0,""));//输出true或false,代表有没有解
        dfs(0,"");
    }
    console.log(res);
}()

华为OD,我昵称“od400” 文章被收录于专栏

华为OD机试刷题历程,因涉及华为权益,牛客不允许更新了。我昵称“od400”,某博客继续更新。

全部评论

相关推荐

评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务