"Leetcode" "Python" Minimum Path Sum

Source: Internet
Author: User

This problem is not difficult, you can use DFS to do, you can also use dynamic planning, but obviously DFS performance is inferior to DP.

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.

Dynamic planning:

Use dis[x][y] to indicate the shortest distance to reach (x, y), because only right and down, so the smaller values of dis (x, y) = Dis[x-1][y] and dis[x][y-1] plus a (x, y). Final conversion to DIS (m-1,n-1)

Class Solution {public:    int minpathsum (vector<vector<int> > &grid) {        int mm=grid.size ();        int nn=grid[0].size ();        vector<vector<int> > Dis;        Vector<int> Vec;        Vec.push_back (Grid[0][0]);        for (int i=1;i<nn;i++) {            vec.push_back (vec[i-1]+grid[0][i]);        }        Dis.push_back (VEC);        for (int i=1;i<mm;i++) {            vec.clear ();            for (int j=0;j<nn;j++) {                if (j==0)   vec.push_back (Dis[i-1][j]+grid[i][j]);                else    vec.push_back (min (dis[i-1][j],vec[j-1]) +grid[i][j]);            }            Dis.push_back (VEC);        }        return dis[mm-1][nn-1];}    ;

In addition to this, you should pay attention to a lot of details, several submissions can not be passed because the relationship between VEC and dis is not handled well. Long time no use of C + + to do the problem, vector has not been the push value is not through direct access to the subscript to assign value, which requires special attention.

"Leetcode" "Python" 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.