Browse Source

#feat:leetcode p64题题解

yangyi 2 tuần trước cách đây
mục cha
commit
df5229574e
2 tập tin đã thay đổi với 79 bổ sung0 xóa
  1. 38 0
      src/leetcode/p64/Solution.java
  2. 41 0
      src/leetcode/p64/SolutionTest.java

+ 38 - 0
src/leetcode/p64/Solution.java

@@ -0,0 +1,38 @@
+package leetcode.p64;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/23 22:07
+ * @Description: https://leetcode.cn/problems/minimum-path-sum/description/
+ * 64. 最小路径和
+ */
+public class Solution {
+    private int[][] dp;
+    public int minPathSum(int[][] grid) {
+        /**
+         * 记忆化搜索
+         */
+        dp = new int[grid.length][grid[0].length];
+        return dfs(grid.length-1,grid[0].length-1,grid);
+    }
+
+    private int dfs(int x, int y, int[][] grid) {
+        if (x == 0 && y == 0) {
+            return grid[0][0];
+        }
+        if (dp[x][y] != 0) {
+            return dp[x][y];
+        }
+        int res = Integer.MAX_VALUE;
+        if (x > 0) {
+            res = Math.min(res,dfs(x-1,y,grid)+grid[x][y]);
+        }
+        if (y > 0) {
+            res = Math.min(res,dfs(x,y-1,grid)+grid[x][y]);
+        }
+        dp[x][y] = res;
+        return res;
+    }
+}

+ 41 - 0
src/leetcode/p64/SolutionTest.java

@@ -0,0 +1,41 @@
+package leetcode.p64;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/23 22:12
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[][] grid;
+    private int expect;
+
+    public SolutionTest(int[][] grid, int expect) {
+        this.grid = grid;
+        this.expect = expect;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[][]{{1,3,1},{1,5,1},{4,2,1}},7},
+                {new int[][]{{1,2,3},{4,5,6}},12},
+        });
+    }
+
+    @Test
+    public void minPathSum() {
+        assertEquals(expect,solution.minPathSum(grid));
+    }
+}