Skip to main content
Back to problems
#679
Hard Algorithms

24 game

Array Math Backtracking
59.3% acceptance
Feb 20, 2026
1888
288
Given 4 cards with numbers, use +, -, *, / and parentheses to get 24. Return true if possible.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn judge_point24(cards: Vec<i32>) -> bool {
    let nums: Vec<f64> = cards.iter().map(|&x| x as f64).collect();
    Self::solve(&nums)
  }

  fn solve(nums: &[f64]) -> bool {
    if nums.len() == 1 {
      return (nums[0] - 24.0).abs() < 1e-6;
    }
    let n = nums.len();
    for i in 0..n {
      for j in 0..n {
        if i == j { continue; }
        let mut next: Vec<f64> = nums.iter().enumerate()
          .filter(|&(k, _)| k != i && k != j)
          .map(|(_, &v)| v)
          .collect();
        let (a, b) = (nums[i], nums[j]);
        for op in 0..4 {
          let result = match op {
            0 => a + b,
            1 => a - b,
            2 => a * b,
            3 => if b.abs() > 1e-9 { a / b } else { f64::NAN },
            _ => unreachable!(),
          };
          if result.is_nan() { continue; }
          next.push(result);
          if Self::solve(&next) { return true; }
          next.pop();
        }
      }
    }
    false
  }
}