C++ dp solution, beats 100.00%, O(n) space


  • 0
    I
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> dp(2, vector<int>(n, 0));
        dp[0][0] = grid[0][0];
        for (int i = 1; i < n; i++) dp[0][i] = grid[0][i] + dp[0][i - 1];
        int idx = 1;
        for (int i = 1; i < m; i++, idx = 1 - idx) {
            dp[idx][0] = dp[1 - idx][0] + grid[i][0];
            for (int j = 1; j < n; j++) {
                dp[idx][j] = min(dp[1 - idx][j], dp[idx][j - 1]) + grid[i][j];
            }
        }
        return dp[1 - idx][n - 1];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.