JavsScript题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout, }); rl.on('line', (line) => { const res = dfs(line.split(' ')); console.log(res); }); function dfs(nums) { if (nums.length == 1) { return nums[0] == 24; } for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { const a = parseInt(nums[i]); const b = parseInt(nums[j]); let temp = []; if (nums.length > 2) { for (let k = 0; k < nums.length; k++) { if (k != i && k != j) { temp.push(nums[k]); } } } let c = 0; c = a + b; if (dfs([...temp, c])) return true; c = a - b; if (dfs([...temp, c])) return true; c = a * b; if (dfs([...temp, c])) return true; if (b != 0) { c = a / b; if (dfs([...temp, c])) return true; } } } return false; }
思路:
3 9 3 4
12 3 4
...
12 12
24
实现上面的步骤,从四个数中取两个数a, b,与剩下的数组成新的组合。
a b 可能经过 + - * \ 四个有可能的步骤,调用递归
终止条件就是组合中只有一个数时,判断这个数是不是等于24
返回类型 true / false