Skip to content

Commit 6aae667

Browse files
Added solutions
1 parent 2af3fba commit 6aae667

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

minimum_path_sum.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
/*
3+
int minPathSum(vector<vector<int>>& grid) {
4+
// DP problem
5+
// DP[i,j] -> minimum sum of reaching i,j
6+
int rows = grid.size();
7+
int cols = grid[0].size();
8+
9+
// DP grid (rows X cols) initialized to grid[0][0] element
10+
vector<vector<int>> DP(rows,vector<int>(cols,grid[0][0]));
11+
12+
// Fill first column (0)
13+
// DP[i,0] = prefix sum along first column = DP[i-1,0] + grid[i][0]
14+
for (int i=1;i<rows;++i) {
15+
DP[i][0] = DP[i-1][0] + grid[i][0];
16+
}
17+
18+
// Fill first row (0)
19+
// DP[0,i] = prefix sum along first row = DP[0,i-1] + grid[0][i]
20+
for (int i=1;i<cols;++i) {
21+
DP[0][i] = DP[0][i-1] + grid[0][i];
22+
}
23+
24+
// Fill the rest of the matrix
25+
// We can only go right and down
26+
// i,j can be reached from the above it (i-1,j) OR from its left (i,j-1)
27+
// We minimize the cost for both
28+
for (int i=1;i<rows;++i) {
29+
for (int j=1;j<cols;++j) {
30+
DP[i][j] = min(DP[i-1][j],DP[i][j-1]) + grid[i][j];
31+
}
32+
}
33+
34+
// return
35+
return DP[rows-1][cols-1];
36+
}
37+
38+
*/

0 commit comments

Comments
 (0)