Javascript recursive solution


  • 1
    L
    var judgePoint24 = function(cards) {
      if(cards.length===1) {
        var roundValue = Math.round(cards[0]*100)/100;
        return roundValue === 24;
      }
    
      for(var i=0; i<cards.length; i++) {
        for(var j=0; j<cards.length; j++) {
          if(i===j) continue;
          var small = Math.min(i,j);
          var large = Math.max(i,j);
          var thisCards = cards.slice();
          thisCards.splice(large,1);
          thisCards.splice(small,1);
    
          var iValue = cards[i];
          var jValue = cards[j];
          var isValid = false;
          isValid = isValid || judgePoint24( [iValue+jValue, ...thisCards] );
          isValid = isValid || judgePoint24( [iValue-jValue, ...thisCards] );
          isValid = isValid || judgePoint24( [iValue*jValue, ...thisCards] );
          if(jValue !==0) {
            isValid = isValid || judgePoint24( [iValue/jValue, ...thisCards] );
          }
          if(isValid) return true;
        }
      }
      return false;
    };
    

  • 0
    Y

    +1 for var roundValue = Math.round(cards[0]*100)/100;

    How did you think of that?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.