Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created January 21, 2020 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/86ba1bc4947241f95564795f4eac94a9 to your computer and use it in GitHub Desktop.
Save adamkorg/86ba1bc4947241f95564795f4eac94a9 to your computer and use it in GitHub Desktop.
Leetcode 64: Minimum Path Sum (iterative dp)
#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;
vector<vector<int>> dp(rows, vector<int>(cols, 0));
dp[0][0] = grid[0][0];
for (int c=1; c<cols; ++c)
dp[0][c] = dp[0][c-1] + grid[0][c];
for (int r=1; r<rows; ++r)
dp[r][0] = dp[r-1][0] + grid[r][0];
for (int r=1; r<rows; ++r) {
for (int c=1; c<cols; ++c)
dp[r][c] = min(dp[r-1][c], dp[r][c-1]) + grid[r][c];
}
return dp[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