Created
January 21, 2020 22:26
-
-
Save adamkorg/1ecdf072939952365115be612338dd99 to your computer and use it in GitHub Desktop.
Leetcode 64: Minimum Path Sum (iterative dp, const aux space)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
int minPathSum(vector<vector<int>>& grid) { | |
int rows = grid.size(); | |
if (rows == 0) return 0; | |
int cols = grid[0].size(); | |
if (cols == 0) return 0; | |
for (int c=1; c<cols; ++c) | |
grid[0][c] = grid[0][c-1] + grid[0][c]; | |
for (int r=1; r<rows; ++r) | |
grid[r][0] = grid[r-1][0] + grid[r][0]; | |
for (int r=1; r<rows; ++r) { | |
for (int c=1; c<cols; ++c) | |
grid[r][c] = min(grid[r-1][c], grid[r][c-1]) + grid[r][c]; | |
} | |
return grid[rows-1][cols-1]; | |
} | |
int main() { | |
vector<vector<int>> grid {{1,3,1},{1,5,1},{4,2,1}}; | |
cout << minPathSum(grid) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment