题解 | #24点游戏算法#leetcode 679 递归

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.on('line', function(line){
    let nums = line.split(' ').map(e=>Number(e));
    let res = judgePoint24(nums);
    console.log(res);
});

function judgePoint24(nums){
   let len = nums.length;
   if(len === 1){
     return Math.abs(nums[0] - 24) < 0.000000001;
   } 
   let isValid = false;
   for(let i=0; i<len; i++){
       for(let j=i+1; j<len; j++){
           const n1 = nums[i];
           const n2 = nums[j];
           const newNums = [];
           for(let k=0; k<len; k++){
               if(k !== i && k !== j){
                  newNums.push(nums[k]);
               }
           }
           isValid = isValid || judgePoint24([...newNums, n1 + n2]);
           isValid = isValid || judgePoint24([...newNums, n1 - n2]);
           isValid = isValid || judgePoint24([...newNums, n2 - n1]);
           isValid = isValid || judgePoint24([...newNums, n1 * n2]);
           if(n1 !== 0){
              isValid = isValid || judgePoint24([...newNums, n2 / n1]);
           }
           if(n2 !== 0){
               isValid = isValid || judgePoint24([...newNums, n1 / n2]);
           }
           
           if(isValid){
               return true;
           }
       }
   }
    return false;
}

#华为笔试#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务