Minimum Path Sum最小路径和算法详解

问题详见: 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.

解题思路:

      由题可知,如果只有一行或者一列,直接将所有元素相加即为最短路径和。然后动态方程是sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];,即要么从左边,要么从上边到达遍历到的点。整个算法复杂度为 O(mn) 。具体算法如下:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size(); 
        vector<vector<int> > sum(m, vector<int>(n, grid[0][0]));
        for (int i = 1; i < m; i++)
            sum[i][0] = sum[i - 1][0] + grid[i][0];
        for (int j = 1; j < n; j++)
            sum[0][j] = sum[0][j - 1] + grid[0][j];
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                sum[i][j]  = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
        return sum[m - 1][n - 1];
    }
};

其提交运行结果如下:
Minimum Path Sum最小路径和算法详解_第1张图片

你可能感兴趣的:(C++,算法,C++,算法)