enum Operation { Add, Subtract, Multiply, Divide, } enum Card { Int(i32), Op(Operation), } struct Solution; impl Solution { fn solve(cards: &Vec) -> bool { let mut stack = Vec::new(); for t in cards.iter() { if let Card::Op(op) = t { if stack.len() < 2 { return false; } let b = stack.pop().unwrap() as f64; let a = stack.pop().unwrap() as f64; let result = match op { Operation::Add => a + b, Operation::Subtract => a - b, Operation::Multiply => a * b, Operation::Divide => { if b == 0f64 { return false; } a / b } }; stack.push(result); } else if let Card::Int(num) = t { stack.push(*num as f64); } } if stack.len() != 1 { return false; } (24f64 - stack[0]).abs() < 1e-5 } fn dfs(cards: &Vec, card_objects: &mut Vec, visited: &mut Vec) -> bool { if card_objects.len() == 7 { return Self::solve(card_objects); } for i in 0..8 { if i <= 3 { if visited[i] { continue; } visited[i] = true; card_objects.push(Card::Int(cards[i])); if Self::dfs(cards, card_objects, visited) { return true; } card_objects.pop(); visited[i] = false; } else { let op = match i { 4 => Operation::Add, 5 => Operation::Subtract, 6 => Operation::Multiply, _ => Operation::Divide, }; card_objects.push(Card::Op(op)); if Self::dfs(cards, card_objects, visited) { return true; } card_objects.pop(); } } false } pub fn judge_point24(cards: Vec) -> bool { let mut visited = vec![false; 4]; let mut card_objects = Vec::new(); for i in 0..4 { visited[i] = true; card_objects.push(Card::Int(cards[i])); for j in 0..4 { if visited[j] { continue; } else { visited[j] = true; card_objects.push(Card::Int(cards[j])); if Self::dfs(&cards, &mut card_objects, &mut visited) { return true; } card_objects.pop(); visited[j] = false; } } card_objects.pop(); visited[i] = false; } false } } fn main() { let sl = Solution::judge_point24(vec![3,3,8,8]); println!("{:?}", sl); }