题目描述:
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.
解题思路:
动态规划,算出所有位置到起点的最小距离
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 int m = grid.size(); 5 if (m == 0) { 6 return 0; 7 } 8 9 int n = grid[0].size(); 10 11 for (int i = 1; i < m; ++i) { 12 grid[i][0] += grid[i - 1][0]; 13 } 14 15 for (int i = 1; i < n; ++i) { 16 grid[0][i] += grid[0][i - 1]; 17 } 18 19 for (int i = 1; i < m; ++i) { 20 for (int j = 1; j < n; ++j) { 21 grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]); 22 } 23 } 24 25 return grid[m - 1][n - 1]; 26 } 27 };