Problem:
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.
Analysis:
Simple DP problem, always choose the minimum path preceed the current position.
Code:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int> > &grid) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int m = grid.size(); 7 int n = grid[0].size(); 8 int tab[m][n]; 9 10 tab[0][0] = grid[0][0]; 11 for (int i=1; i<n; i++) 12 tab[0][i] = tab[0][i-1] + grid[0][i]; 13 14 for (int i=1; i<m; i++) 15 tab[i][0] = tab[i-1][0] + grid[i][0]; 16 17 for (int i=1; i<m; i++) 18 for (int j=1; j<n; j++) { 19 tab[i][j] = min(tab[i][j-1], tab[i-1][j]) + grid[i][j]; 20 } 21 22 return tab[m-1][n-1]; 23 } 24 25 int min(int &a, int &b) { 26 return (a<b)?a:b; 27 } 28 };