64. 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.

简单原始的动态规划算法

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(grid.empty())    return 0;

        int row = grid.size();
        int col = grid[0].size();
        vector<vector<int>> dp(grid.size(), vector<int>(grid[0].size(), INT_MAX));

        dp[0][0] = grid[0][0];
        for(int i = 1; i < grid[0].size(); i++){
            dp[0][i] = dp[0][i -1] + grid[0][i];
        }

        for(int i = 1; i < grid.size(); i++){
            dp[i][0] = dp[i- 1][0] + grid[i][0];
        }

        for(int i = 1; i < grid.size(); i++)
            for(int j = 1; j < grid[0].size(); j++){
                dp[i][j] = min(dp[i - 1][j] + grid[i][j], dp[i][j - 1]+ grid[i][j]);
            }

        return dp[row - 1][col - 1];
    }
};

压缩矩阵空间

我们发现只使用一行或者一列就能保存全部的上一状态
使用行或列中的最小的来生成dp;

假设使用行来生成

7,0,8,8,0,3,5,8,5,4
4,1,2,9,9,6,0,8,6,9
9,7,1,1,0,1,2,4,1,7


dp[i]表示第i行,
刚开始,dp[i]初始化为第0列的所有的值,遍历过程中,
dp[i] = min(dp[i - 1], dp[i]) + grid[i][]
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int row = grid.size();
        int col = grid[0].size();
        if( row == 0 || col == 0)    return 0;

        vector<int> dp(row, INT_MAX);
        dp[0] = grid[0][0];

        for(int i = 1; i < row; i++){
            dp[i] = dp[i - 1] + grid[i][0];
            std::cout<<dp[i]<<std::endl;
        }

        for(int i = 1; i < col; i++){
            dp[0] = dp[0] + grid[0][i];
            for(int j = 1; j < row; j++){
                dp[j] = min(dp[j - 1], dp[j]) + grid[j][i];
            }
        }

        return dp[row - 1];
    }
};

空间复杂度

$$O(min(row, col))$$

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int row = grid.size();
        int col =grid[0].size();

        if(row == 0 || col == 0)
            return 0;

        int more = max(row, col);
        int less = min(row, col);

        int rowB = (more == row);

        vector<int> dp(less, INT_MAX);

        dp[0] = grid[0][0];
        for(int i = 1; i < less; i++){
            dp[i] = dp[i - 1] + (rowB?grid[0][i]:grid[i][0]);
        }

        for(int i = 1; i < more; i++){
            dp[0] = dp[0] + (rowB?grid[i][0]:grid[0][i]);
            for(int j = 1; j < less; j++){
                dp[j] = min(dp[j - 1], dp[j]) + (rowB?grid[i][j]:grid[j][i]);
            }
        }
        return dp[less - 1];
    }
};

results matching ""

    No results matching ""