【LeetCode】127.Minimum Path Sum
阿新 • • 發佈:2018-11-13
題目描述(Medium)
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.
題目連結
https://leetcode.com/problems/minimum-path-sum/description/
Example 1:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
演算法分析
對每一行有路徑轉移方程path[j] = min(path[j], path[j - 1]) + grid[i][j],path[j]代表當前行每一列的最小到達路徑。
提交程式碼:
class Solution { public: int minPathSum(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); vector<int> path(n, INT_MAX); path[0] = 0; for (int i = 0; i < m; ++i) { path[0] += grid[i][0]; for (int j = 1; j < n; ++j) { path[j] = min(path[j], path[j - 1]) + grid[i][j]; } } return path[n - 1]; } };