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.
Hide TagsArray Dynamic ProgrammingTest instructions: Looking for a weighted minimum path from the top left of the matrix to the bottom right
Thinking:
(1) The path problem of the matrix (the total number of paths, the total number of paths with obstacles, the weighted minimum, the maximum path, etc.), because of the clear and simple State transfer formula,
All can be solved by DP method, the time complexity is O (m*n)
(2) solve the global optimal problem with DP!! Whether the problem has local optimal solution, State transfer formula: A[i][j] = min (A[i-1][j], a[i][j-1]) + grid[i][j];
The choice of each step is defined as the optimal solution, so the local optimization is established
Code
Class Solution {public: int minpathsum (vector<vector<int> > &grid) { vector<vector<int > >::const_iterator con_it=grid.begin (); int m=grid.size (); int n= (*CON_IT). Size (); vector<int> tmp (n,0); Vector<vector<int> > A (m,tmp); if (m==0 | | n==0) return 0; A[0][0]=GRID[0][0]; for (int i=1;i<m;i++) a[i][0]=a[i-1][0]+grid[i][0]; for (int j=1;j<n;j++) a[0][j]=a[0][j-1]+grid[0][j]; for (int i = 1; i < m; i++) for (int j = 1; j < N; j + +) a[i][j] = min (A[i-1][j], a[i][j-1]) + Grid[i][j];
return a[m-1][n-1]; };
Leetcode | | 64. Minimum Path Sum