LC 64. Minimum Path Sum
阿新 • • 發佈:2018-12-11
1. 題目描述
64. Minimum Path Sum
Medium
98225
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.
2.解題思路
dp陣列記錄到達(i,j)最短路徑。因為題目規定只能向右走或者向下走,dp[ i ][ j ] = min ( dp[ i-1][ j ], dp[ i ][ j-1] ) + (i, j)本身的數值。要注意第一行的元素只能由其左邊元素向右走到達,第一列元素只能由其上面元素向下走到達。
3.實現程式碼
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int row = grid.size(), col = grid[0].size(); int dp[row][col]; memset(dp, 0, sizeof(dp)); dp[0][0] = grid[0][0]; for (int i=1; i<col; i++) {//根據題意只能向下或向右走,所以第一行只能從(0,0)向右走到達 dp[0][i] = dp[0][i-1]+grid[0][i]; } for (int i=1; i<row; i++) { for (int j=0; j<col; j++) { if (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[row-1][col-1]; } };