Compare commits

...

2 Commits

Author SHA1 Message Date
li-chx f29016175d 54. 螺旋矩阵 2025-09-04 11:31:56 +08:00
li-chx 44119f4286 679. 24 点游戏 2025-08-18 14:16:41 +08:00
1 changed files with 53 additions and 20 deletions

View File

@ -1,29 +1,62 @@
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];
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
let mut top_x = 0;
let mut left_y = 0;
let mut bottom_x = matrix.len() as i32 - 1;
let mut right_y = matrix[0].len() as i32 - 1;
let mut next_x = 0;
let mut next_y = 1;
let mut pos = (0, 0);
let mut res = vec![matrix[0][0]];
let mut next_pos = || {
let mut new_pos = (pos.0 + next_x, pos.1 + next_y);
if new_pos.0 > bottom_x || new_pos.0 < top_x || new_pos.1 > right_y || new_pos.1 < left_y {
(next_x, next_y) = match (next_x, next_y) {
(0, 1) => {
top_x += 1;
(1, 0)
}
(1, 0) => {
right_y -= 1;
(0, -1)
}
(0, -1) => {
bottom_x -= 1;
(-1, 0)
}
(-1, 0) => {
left_y += 1;
(0, 1)
}
_ => (0, 0),
};
new_pos = (pos.0 + next_x, pos.1 + next_y);
if new_pos.0 > bottom_x
|| new_pos.0 < top_x
|| new_pos.1 > right_y
|| new_pos.1 < left_y
{
return false;
}
}
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;
}
mem[0]
pos = new_pos;
res.push(matrix[pos.0 as usize][pos.1 as usize]);
true
};
while next_pos() {}
res
}
}
fn main() {
let sl = Solution::new21_game(21, 17, 10);
let sl = Solution::spiral_order(vec![
vec![1, 2, 3, 4],
vec![5, 6, 7, 8],
vec![9, 10, 11, 12],
]);
println!("{:?}", sl);
}