Leetcode first _ Minimum Path Sum

Source: Internet
Author: User

It can be written recursively and concisely, but Will time out.

Dp. This problem needs to be calculated from the back. The small scale in the bottom right corner is known, and the boundary is also very obvious. It is the last row and the last column, the restriction on the walking direction determines that the routing of these locations is unique and can be calculated first. And then continue to calculate.

Use distance [I] [j] To save the shortest distance from the current position to the bottom right corner, the state transition equation selects a small one from distance [I + 1] [j] and distance [I] [j + 1], and then adds its own.

The code is easy to understand. This is the charm of dp. Space can be optimized, because the current status is only related to the last row and the next column.

class Solution {public:    int minPathSum(vector<vector<int> > &grid) {        int erow = grid.size();        if(erow<=0)  return 0;        int ecolumn = grid[0].size();        if(ecolumn<=0)   return 0;        if(erow==1&&ecolumn==1) return grid[0][0];        vector<int> tpres(ecolumn, 0);        vector<vector<int> > distance(erow, tpres);        distance[erow-1][ecolumn-1] = grid[erow-1][ecolumn-1];        for(int i=erow-2;i>=0;i--)            distance[i][ecolumn-1] = distance[i+1][ecolumn-1] + grid[i][ecolumn-1];        for(int i=ecolumn-2;i>=0;i--)            distance[erow-1][i] = distance[erow-1][i+1] + grid[erow-1][i];        for(int i=erow-2;i>=0;i--){            for(int j=ecolumn-2;j>=0;j--){                distance[i][j] = min(distance[i+1][j], distance[i][j+1])+grid[i][j];            }        }        return distance[0][0];    }};


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.