Find the Kth Smallest Sum of a Matrix With Sorted Rows LeetCode solution in Rust
1use std::collections::{BinaryHeap, HashSet};23impl Solution {4pub fn kth_smallest(mat: Vec<Vec<i32>>, k: i32) -> i32 {5let mut heap = BinaryHeap::new();6let mut set = HashSet::new();7let width = mat[0].len() - 1;8heap.push((9-mat.iter().map(|row| row[0]).sum::<i32>(),10vec![0; mat.len()],11));12for _ in 1..k {13let (cur, ind) = heap.pop().unwrap();14for r in 0..ind.len() {15if ind[r] < width {16let mut tmp = ind.clone();17tmp[r] += 1;18if !set.contains(&tmp) {19set.insert(tmp.clone());20heap.push((cur + mat[r][tmp[r] - 1] - mat[r][tmp[r]], tmp));21}22}23}24}25-heap.pop().unwrap().026}27}