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]
标签:int,Sum,路径,最小,Minimum,grid,Path,64,dp
From: https://www.cnblogs.com/douniwanli/p/18192454