[Leetcode] 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.
题意:求矩阵中从左上角到右下角的最小路径和。
思路:这题的思路和unique paths的类似。维护一个二维数组dp,其中dp[i][j]表示到达点(i,j)的最小路径和。首先考虑初始条件;然后初始化,二维数组中,第一行、第一列,如何初始?因为只能向右或者想下移动一个位置,所以,第一行,只能从左到右;第一列只能从上到下。对于一般点,到达该点只能从左边或者上边到达,则,到达该点的最小路径和,为dp[i][j]=min(dp[i][j-1],dp[i-1][j])+grid[i][j]。代码如下:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int> > &grid) 4 { 5 int row=grid.size(),col=grid[0].size(); 6 if(row==0||col==0) return 0; 7 vector<vector<int>> dp(row,vector<int>(col,0)); 8 dp[0][0]=grid[0][0]; 9 10 for(int i=1;i<row;++i) 11 dp[i][0]=dp[i-1][0]+grid[i][0]; 12 for(int i=1;i<col;++i) 13 dp[0][i]=dp[0][i-1]+grid[0][i]; 14 15 for(int i=1;i<row;++i) 16 { 17 for(int j=1;j<col;++j) 18 { 19 dp[i][j]=min(dp[i][j-1],dp[i-1][j])+grid[i][j]; 20 } 21 } 22 return dp[row-1][col-1]; 23 } 24 };