题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
dfs 暴力
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.on("line", function (line) { let m = { 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, J: 11, Q: 12, K: 13, A: 1, 2: 2, }; let data = line.trim().split(" "); let res = "NONE"; if (data.includes("joker") || data.includes("JOKER")) { return console.log("ERROR"); } // 深度遍历 function dfs(step, sum, arr, s) { if (sum == 24 && step == 4) { return (res = s); } else { step++; for (let i = 0; i < arr.length; i++) { let _arr = arr.slice(); _arr.splice(i, 1); let num = m[arr[i]]; if (step == 1) { dfs(step, num, _arr, `${arr[i]}`); } else { dfs(step, sum + num, _arr, `${s}+${arr[i]}`); dfs(step, sum - num, _arr, `${s}-${arr[i]}`); dfs(step, sum * num, _arr, `${s}*${arr[i]}`); dfs(step, sum / num, _arr, `${s}/${arr[i]}`); } } } } dfs(0, 0, data, ""); console.log(res); });