679. 24 Game #2068
-
Topics: You are given an integer array You are restricted with the following rules:
Return Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if we can use four given numbers (each between 1 and 9) and the operators '+', '-', '*', '/' along with parentheses to form an expression that evaluates to 24. The solution involves exploring all possible combinations of these numbers and operations using a backtracking approach. Approach
Let's implement this solution in PHP: 679. 24 Game <?php
/**
* @param Integer[] $cards
* @return Boolean
*/
function judgePoint24($cards) {
return judge($cards);
}
/**
* @param $nums
* @return bool
*/
function judge($nums) {
$n = count($nums);
if ($n == 1) {
return abs($nums[0] - 24) < 1e-6;
}
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
$next = [];
for ($k = 0; $k < $n; $k++) {
if ($k != $i && $k != $j) {
$next[] = $nums[$k];
}
}
$a = $nums[$i];
$b = $nums[$j];
$values = [
$a + $b,
$a * $b,
$a - $b,
$b - $a
];
if (abs($b) > 1e-6) {
$values[] = $a / $b;
}
if (abs($a) > 1e-6) {
$values[] = $b / $a;
}
foreach ($values as $val) {
$nextArr = $next;
$nextArr[] = $val;
if (judge($nextArr)) {
return true;
}
}
}
}
return false;
}
// Test cases
$cards1 = [4, 1, 8, 7];
var_dump(judgePoint24($cards1)); // true
$cards2 = [1, 2, 1, 2];
var_dump(judgePoint24($cards2)); // false
?> Explanation:
This approach efficiently explores all potential expressions by leveraging recursion and backtracking, ensuring correctness while handling floating-point precision and division constraints appropriately. |
Beta Was this translation helpful? Give feedback.
We need to determine if we can use four given numbers (each between 1 and 9) and the operators '+', '-', '*', '/' along with parentheses to form an expression that evaluates to 24. The solution involves exploring all possible combinations of these numbers and operations using a backtracking approach.
Approach