implSolution{pubfnjudge_point24(cards:Vec<i32>)->bool{letnums:Vec<f64>=cards.iter().map(|&x|xasf64).collect();Self::dfs(nums)}fndfs(nums:Vec<f64>)->bool{ifnums.len()==1{return(nums[0]-24.0).abs()<1e-6;}letn=nums.len();foriin0..n{forjin(i+1)..n{leta=nums[i];letb=nums[j];// Collect the remaining numbersletrest:Vec<f64>=nums.iter().enumerate().filter(|&(k,_)|k!=i&&k!=j).map(|(_,&v)|v).collect();// All possible results of combining a and bletmutcandidates=vec![a+b,a-b,b-a,a*b];ifb.abs()>1e-6{candidates.push(a/b);}ifa.abs()>1e-6{candidates.push(b/a);}forcincandidates{letmutnext=rest.clone();next.push(c);ifSelf::dfs(next){returntrue;}}}}false}}Explanation
· Type choice: f64 is used because division can produce non-integer intermediate values (e.g. 8 / (3 - 8/3) = 24).
· Recursion: dfs tries every pair (i, j) of current numbers, combines them with +, -, *, /, and recurses with the new list. When only one number remains, we check whether it’s approximately 24.
· Division: We skip division when the denominator is essentially zero to avoid NaN/Infinity.
· Floating-point comparison: Uses 1e-6 tolerance instead of == 24.0.
Complexity
· Time: O(1) in practice — for n = 4 cards, at each level we choose a pair and combine, giving roughly 6 × 6 × 4 × 4 × 3 × 4 × 2 × 4 ≈ 55k operations in the worst case.
· Space: O(n) recursion depth (n = 4), plus small vector clones.