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.

分析:

好久不做4要素分析,这里写一个:

(1) state: f[i][j] 到坐标(i, j)的minimum path sum

(2) function: f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]

(3) initialization: f[i][0], f[0][j]

(4) answer: f[m - 1][n - 1]

解法:

class Solution {
public:
    /**
     * @param grid: a list of lists of integers.
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    int minPathSum(vector<vector<int> > &grid) {
        // write your code here
        int m = grid.size();
        if (m == 0) {
            return 0;
        }
        int n = grid[0].size();
        if (n == 0) {
            return 0;
        }

        vector<vector<int> > pathSum(m, vector<int>(n, INT_MAX) );
        pathSum[0][0] = grid[0][0];
        for (int i = 1; i < m; i++) {
            pathSum[i][0] = pathSum[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < n; i++) {
            pathSum[0][i] = pathSum[0][i - 1] + grid[0][i];
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                pathSum[i][j] = min(pathSum[i - 1][j], pathSum[i][j - 1]) + grid[i][j];
            }
        }

        return pathSum[m - 1][n - 1];
    }
};

results matching ""

    No results matching ""