Skip to content

Commit aa53760

Browse files
Added minimum path sum problem solution in cpp
1 parent 24536f0 commit aa53760

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// 64. Minimum Path Sum
2+
// Medium
3+
4+
// 8794
5+
6+
// 113
7+
8+
// Add to List
9+
10+
// Share
11+
// Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
12+
13+
// Note: You can only move either down or right at any point in time.
14+
15+
16+
17+
// Example 1:
18+
19+
20+
// Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
21+
// Output: 7
22+
// Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
23+
// Example 2:
24+
25+
// Input: grid = [[1,2,3],[4,5,6]]
26+
// Output: 12
27+
28+
29+
// Constraints:
30+
31+
// m == grid.length
32+
// n == grid[i].length
33+
// 1 <= m, n <= 200
34+
// 0 <= grid[i][j] <= 100
35+
36+
class Solution {
37+
public:
38+
int solve(vector<vector<int>>&grid,int n,int m, int i,int j, vector<vector<int>>&dp){
39+
if(i<0 || j<0 || i>=n || j>=m)return 100000000;
40+
if(dp[i][j]!=-1)return dp[i][j];
41+
if(i==n-1 && j==m-1){
42+
return grid[i][j];
43+
}
44+
int ans=solve(grid,n,m,i,j+1, dp)+grid[i][j];
45+
ans=min(ans,solve(grid,n,m,i+1,j, dp)+grid[i][j]);
46+
dp[i][j]=ans;
47+
return ans;
48+
}
49+
int minPathSum(vector<vector<int>>& grid) {
50+
int n=grid.size();
51+
int m=grid[0].size();
52+
vector<vector<int>>dp(n,vector<int>(m,-1));
53+
return solve(grid,n,m,0,0,dp);
54+
}
55+
};

0 commit comments

Comments
 (0)