Explorar el Código

feat: dungeon_game

Zhang Li hace 10 meses
padre
commit
5fa363f868
Se han modificado 2 ficheros con 34 adiciones y 1 borrados
  1. 32 0
      src/solutions/dp/dungeon_game.rs
  2. 2 1
      src/solutions/dp/mod.rs

+ 32 - 0
src/solutions/dp/dungeon_game.rs

@@ -0,0 +1,32 @@
+struct Solution;
+
+impl Solution {
+    pub fn calculate_minimum_hp(dungeon: Vec<Vec<i32>>) -> i32 {
+        let rows = dungeon.len();
+        let cols = dungeon[0].len();
+        let mut dp = vec![vec![i32::MAX; cols+1]; rows+1];
+        dp[rows-1][cols] = 1;
+        dp[rows][cols-1] = 1;
+        for i in (0..rows).rev() {
+            for j in (0..cols).rev() {
+                dp[i][j] = (dp[i][j+1].min(dp[i+1][j]) - dungeon[i][j]).max(1);
+            }
+
+        }
+
+        dp[0][0]
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_calculate_minimum_hp() {
+        let dungeon = vec![vec![-2,-3,3],vec![-5,-10,1],vec![10,30,-5]];
+        let res = Solution::calculate_minimum_hp(dungeon);
+        assert_eq!(res, 7);
+    }
+}

+ 2 - 1
src/solutions/dp/mod.rs

@@ -19,4 +19,5 @@ mod palindrome_partitioning2;
 mod candy;
 mod candy;
 mod word_break;
 mod word_break;
 mod word_break2;
 mod word_break2;
-mod maximum_product_subarray;
+mod maximum_product_subarray;
+mod dungeon_game;