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.
Note: You can only move either down or right at any point in time.
Solution: Dynamic Programming. Space O(N).
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int> > &grid) { 4 if(grid.empty()) return INT_MIN; 5 int M = grid.size(); 6 int N = grid[0].size(); 7 int dp[N]; 8 dp[0] = grid[0][0]; 9 for(int i = 1; i < N; i++) 10 dp[i] = dp[i-1] + grid[0][i]; 11 12 for(int i = 1; i < M; i++) { 13 dp[0] += grid[i][0]; 14 for(int j = 1; j < N; j++) { 15 dp[j] = min(dp[j-1], dp[j]) + grid[i][j]; 16 } 17 } 18 return dp[N-1]; 19 } 20 };