Description
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.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
分析
题目的意思是:给你一个矩阵,求找一条左上角到右下角的路径,使得路径上的值的和最小。
- 直接动态规划了,这里我没有用额外的dp数组,因为站在当前位置只有两种走法,一个是向右,一个是向下。即grid[i][j]=min(grid[i][j-1],grid[i-1][j])+grid[i][j];
- 另外考虑i=0的情况,j=0的情况和两者都为0的情况就行了。
代码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0&&j==0){
grid[i][j]=grid[i][j];
}else if(i==0){
grid[i][j]=grid[i][j-1]+grid[i][j];
}else if(j==0){
grid[i][j]=grid[i-1][j]+grid[i][j];
}else{
grid[i][j]=min(grid[i][j-1],grid[i-1][j])+grid[i][j];
}
}
}
return grid[m-1][n-1];
}
};
Python代码
dp和grid混到一起可能有点难理解,可以直接拆开。
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
# dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
# dp[0][0]=grid[0][0]
# i==0 dp[i][j]=dp[i][j-1]+grid[i][j]
# j==0 dp[i][j]=dp[i-1][j] + grid[i][j]
m = len(grid)
n = len(grid[0])
dp = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if i==0 and j ==0:
dp[i][j]=grid[i][j]
elif i==0:
dp[i][j]=dp[i][j-1]+grid[i][j]
elif j==0:
dp[i][j]=dp[i-1][j]+grid[i][j]
else:
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
return dp[-1][-1]