凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 64. Minimum Path Sum

分类:algorithm| 发布时间:2017-03-17 14:08:00


题目

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.

题意

m x n 的格子填充了非负整数,找出一个从左上到右下的路径使得所经过的格子的和最小。

解法

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> sums(m, vector<int>(n, 0));
        sums[0][0] = grid[0][0];
        // init first col
        for (int i = 1; i < m; ++i) {
            sums[i][0] = grid[i][0] + sums[i - 1][0];
        }

        // init first row
        for (int i = 1; i < n; ++i) {
            sums[0][i] = grid[0][i] + sums[0][i - 1];
        }

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

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