Created
January 21, 2020 22:21
-
-
Save adamkorg/07467df3ee7a83492d8ac64772b29f69 to your computer and use it in GitHub Desktop.
Leetcode 64: Minimum Path Sum (recursive + dp)
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 count(const vector<vector<int>>& grid, int rows, int cols, int r, int c, vector<vector<int>>& dp) { | |
if (r == rows || c == cols) return INT_MAX; | |
if (r == rows-1 && c == cols-1) return grid[r][c]; | |
if (dp[r][c] != -1) return dp[r][c]; | |
dp[r][c] = min(count(grid,rows,cols,r+1,c,dp),count(grid,rows,cols,r,c+1,dp))+grid[r][c]; | |
return dp[r][c]; | |
} | |
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, -1)); | |
return count(grid, rows, cols, 0, 0, dp); | |
} | |
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