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

全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务