Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active August 18, 2025 16:26
Show Gist options
  • Save tatsuyax25/d0aef879bd04e11e0a4f3170bbdf4948 to your computer and use it in GitHub Desktop.
Save tatsuyax25/d0aef879bd04e11e0a4f3170bbdf4948 to your computer and use it in GitHub Desktop.
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parenthes
/**
* @param {number[]} cards
* @return {boolean}
*/
var judgePoint24 = function(cards) {
// Convert all numbers to floats for real division
const nums = cards.map(num => num * 1.0);
function backtrack(arr) {
// Base case: only one number left, check if it's close to 24
if (arr.length === 1) {
return Math.abs(arr[0] - 24) < 1e-6;
}
// Try every pair of numbers
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) continue;
// Pick two numbers to operate on
const a = arr[i];
const b = arr[j];
// Create a new array without a and b
const rest = [];
for (let k = 0; k < arr.length; k++) {
if (k !== i && k !== j) rest.push(arr[k]);
}
// Try all 4 operations
const candidates = [
a + b,
a - b,
b - a,
a * b,
a / b,
b / a
];
for (const result of candidates) {
// Recurse with the new result added to the remaining numbers
if (backtrack([...rest, result])) return true;
}
}
}
return false;
}
return backtrack(nums);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment