题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
function isGetCorrectVal(nums) {
let flag = false;
const limit = 24;
function calc(list, result) {
if (result > limit) return;
if (result === limit) {
flag = true;
return;
}
for (let i = 0, len = list.length; i < len; i++) {
let newList = list.slice();
newList.splice(i, 1);
if (result === 0) {
calc(newList, list[i]);
} else {
calc(newList, result + list[i]);
calc(newList, result - list[i]);
calc(newList, result * list[i]);
calc(newList, result / list[i]);
calc(newList, list[i] - result);
calc(newList, list[i] / result);
}
}
}
calc(nums, 0);
return flag;
}
while (line = readline()) {
print(isGetCorrectVal(line.split(' ').map(num => parseInt(num, 10))));
}
安克创新 Anker公司福利 767人发布