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.
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.
求从矩阵的左上角到右下角的最小路径和,每次只能向右和向下移动。
C++:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 int n = grid.size() ; 5 int m = grid[0].size() ; 6 vector<int> dp(m+1 , 0) ; 7 dp[0] = grid[0][0] ; 8 for(int j = 1 ; j < m ; j++){ 9 dp[j] = dp[j-1] + grid[0][j] ; 10 } 11 12 for(int i = 1 ; i < n ; i++){ 13 for(int j = 0 ; j < m ; j++){ 14 if(j == 0){ 15 dp[j] = dp[j] + grid[i][j] ; 16 }else{ 17 dp[j] = min(dp[j],dp[j-1]) + grid[i][j] ; 18 } 19 } 20 } 21 return dp[m-1] ; 22 } 23 };