679. 24 点游戏

This commit is contained in:
li-chx 2025-08-18 14:16:41 +08:00
parent da64b06ee9
commit 44119f4286
1 changed files with 95 additions and 18 deletions

View File

@ -1,29 +1,106 @@
enum Operation {
Add,
Subtract,
Multiply,
Divide,
}
enum Card {
Int(i32),
Op(Operation),
}
struct Solution;
impl Solution {
// return type: all situation, not crash situation
pub fn new21_game(n: i32, k: i32, max_pts: i32) -> f64 {
let mut mem = vec![0f64; (k + max_pts + 1) as usize];
for i in k .. k + max_pts + 1 {
mem[i as usize] = if i <= n { 1f64 } else { 0f64 };
}
let mut temp_ans = 0f64;
if(k - 1 >= 0)
{
let i = k - 1;
for j in 1..max_pts + 1 {
temp_ans += mem[(i + j) as usize];
fn solve(cards: &Vec<Card>) -> 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);
}
mem[i as usize] = temp_ans as f64 / max_pts as f64;
}
for i in (0..k - 1).rev() {
temp_ans += mem[(i + 1) as usize] - mem[(i + max_pts + 1) as usize];
mem[i as usize] = temp_ans as f64 / max_pts as f64;
if stack.len() != 1 {
return false;
}
mem[0]
(24f64 - stack[0]).abs() < 1e-5
}
fn dfs(cards: &Vec<i32>, card_objects: &mut Vec<Card>, visited: &mut Vec<bool>) -> 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<i32>) -> 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::new21_game(21, 17, 10);
let sl = Solution::judge_point24(vec![3,3,8,8]);
println!("{:?}", sl);
}