Minimum Path Sum
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.
DP,递推公式f[i][j]=min(f[i-1][j],f[i][j-1])+grid[i][j]。
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 if(grid.size()==0 || grid[0].size()==0) return 0; 5 int m=grid.size(),n=grid[0].size(); 6 vector<vector<int>> f(m,vector<int>(n,0)); 7 f[0][0]=grid[0][0]; 8 for(int i=1;i<n;i++) f[0][i]=f[0][i-1]+grid[0][i]; 9 for(int i=1;i<m;i++) f[i][0]=f[i-1][0]+grid[i][0]; 10 for(int i=1;i<m;i++) 11 { 12 for(int j=1;j<n;j++) 13 { 14 f[i][j]=min(f[i-1][j],f[i][j-1])+grid[i][j]; 15 } 16 } 17 return f[m-1][n-1]; 18 } 19 };