64 - Minimum Path Sum 最小路徑和

金字塔下的蜗牛發表於2024-05-14

64 - Minimum Path Sum 最小路徑和

問題描述

 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.

解釋:
給定m*n 的矩陣,裡面都是非負整數,找到一條從左上角到右下角的路徑,使得其和最小。每一次移動只能向右或者向下移動

案例:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

給定如上陣列,可以明確知道從左上到右下的最小路徑和為圖中黃色圖形

基本思想

二維動態規劃問題,假設grid陣列 m行,n列。構建同等大小的陣列dp

\(dp[i][j]\) : 表示 由 [0,0] 位置 到 [i,j] 位置的最小路徑和,由於只能向下或者向右移動,故 \(dp[i][j]\) 更新公式如下:

\(dp[i][j]\) = min( \(dp[i-1][j]\), \(dp[i][j-1]\)) + \(grid[i][j]\)

時間複雜度,空間複雜度都為\(o(n^2)\)

程式碼

C++

    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        if(m<=0) return 0;
        int n = grid[0].size();
        if(n<=0) return 0;
        vector<vector<int>> dp(m, vector<int>(n,0));
        //1-初始化
        dp[0][0] = grid[0][0];
        for(int i=1;i<m;++i) {
            dp[i][0] = grid[i][0] + dp[i-1][0];
        }
        for(int i=1;i<n;++i) {
            dp[0][i] = dp[0][i-1] + grid[0][i];
        }
        for(int i=1;i<m;++i) {
            for(int j=1;j<n;++j) {
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }

python

    def minPathSum(self, grid: List[List[int]]) -> int:
        m = len(grid)
        if m <= 0: return 0
        n = len(grid[0])
        if n <= 0: return 0
        dp = [[0 for j in range(n)] for i in range(m)]
        dp[0][0] = grid[0][0]
        for i in range(1, m):
            dp[i][0] = dp[i-1][0] + grid[i][0]
        for i in range(1, n):
            dp[0][i] = dp[0][i-1] + grid[0][i]
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
        return dp[m-1][n-1]

相關文章