[Leetcode] minimum path sum

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.