Leetcode: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.

 

解题分析:

每次只能向下或者向右走,其实就是说明了 搜索过程中的状态扩展情况

设 f[i,j]表示 从原点到 grid[i][j]的最小路径和,则有以下动态规划特征式:

f[i,j] = min { f[i-1][j], f[i][j-1] } + grid[i][j]

 

注意边界情况

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        int nRow = grid.size();
        int nCol = 0;
        if (nRow == 0) {
            return 0;
        } else {
            nCol = grid.at(0).size();
        }
        
        vector<vector<int>> path(nRow, vector<int>(nCol, 0));
        for (int i = 0; i < nRow; ++i) {
            for (int j = 0; j < nCol; ++j) {
                if (i == 0 && j == 0) path.at(0).at(0) = grid.at(0).at(0);
                if (i == 0 && j != 0) path.at(i).at(j) = path.at(i).at(j-1) + grid.at(i).at(j);
                if (i != 0 && j == 0) path.at(i).at(j) = path.at(i-1).at(j) + grid.at(i).at(j);
                if (i != 0 && j != 0) path.at(i).at(j) = std::min(path.at(i-1).at(j), path.at(i).at(j-1)) + grid.at(i).at(j);
            }
        }
        return path.at(nRow-1).at(nCol-1);
    }
};

 

你可能感兴趣的:(LeetCode)