Leetcode 题目解析之 Minimum Path Sum

2022-01-09 11:37:56 浏览数 (2)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

建立一个背包dpm,其中dpi表示从grid0到gridi的最小和。

代码语言:txt复制
    public int minPathSum(int[][] grid) {
        if (grid == null || grid[0] == null) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];
        for (int y = 1; y < n; y  ) {
            dp[0][y] = dp[0][y - 1]   grid[0][y];
        }
        for (int x = 1; x < m; x  ) {
            dp[x][0] = dp[x - 1][0]   grid[x][0];
        }
        for (int y = 1; y < n; y  ) {
            for (int x = 1; x < m; x  ) {
                int min = Math.min(dp[x - 1][y], dp[x][y - 1]);
                dp[x][y] = min   grid[x][y];
            }
        }
        return dp[m - 1][n - 1];
    }

0 人点赞