Minimum path sum
GivenMXNGrid filled with non-negative numbers, find a path from top left to bottom right whichMinimizesThe sum of all numbers along its path.
Note:You can only move either down or right at any point in time.
Solution:
Typical dynamic planning. Create M * n matrix minv. minv [I] [J] stores the first element (grid [0] [0]) to the current element (grid [I] [J]). the shortest path length.
For each element, the path is from top or left.
That is, MINV [I] [J] = min (MINV [I-1] [J] + MINV [I] [J-1]) + grid [I] [J].
Do not forget to initialize the first column of the first row.
Class solution {public: int minpathsum (vector <int> & grid) {int M = grid. size (); int n = grid [0]. size (); // DP, stores the shortest path vector from the first element to the element <vector <int> MINV; minv. resize (m); For (vector <int> >:: size_type ST = 0; ST <m; ST ++) MINV [st]. resize (n); MINV [0] [0] = grid [0] [0]; // The first column initializes for (vector <int> :: size_type ST = 1; ST <m; ST ++) MINV [st] [0] = MINV [ST-1] [0] + grid [st] [0]; // initialize for (vector <int>: size_type ST = 1; ST <n; ST ++) MINV [0] [st] = MINV [0] [ST-1] + grid [0] [st]; for (vector <int> >:: size_type ST1 = 1; ST1 <m; ST1 ++) {for (vector <int>: size_type st2 = 1; st2 <n; st2 ++) {MINV [ST1] [st2] = min (MINV [st1-1] [st2], MINV [ST1] [st2-1]) + grid [ST1] [st2];} return MINV [M-1] [n-1] ;}};
[Leetcode] minimum path sum