-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question86.cpp
33 lines (32 loc) · 1.02 KB
/
Question86.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
86 -> Minimum Path Sum
Solution :
class Solution {
public:
// int solve(int i,int j,vector<vector<int>>&grid,vector<vector<int>>&dp){
// if(i==0&&j==0)return grid[0][0];
// if(i<0||j<0)return 1e9;
// if(dp[i][j]!=-1)return dp[i][j];
// int up=grid[i][j]+solve(i-1,j,grid,dp);
// int left=grid[i][j]+solve(i,j-1,grid,dp);
// return dp[i][j]=min(up,left);
// }
int minPathSum(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
vector<vector<int>>dp(m,vector<int>(n,-1));
// return solve(m-1,n-1,grid,dp);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0&&j==0)dp[0][0]=grid[0][0];
else{int up=1e9,left=1e9;
if(i-1>=0)
up=grid[i][j]+dp[i-1][j];
if(j-1>=0)
left=grid[i][j]+dp[i][j-1];
dp[i][j]=min(up,left);
}
}
}
return dp[m-1][n-1];
}
};