[LC] Minimum Path Sum

Source: Internet
Author: User

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 any numbers along its path.

Note: You can only move either down or right at any point in time.

The answer at the beginning is this, it will time out.

Class Solution {public:    int minpathsum (vector<vector<int>>& grid) {        int m = grid. Size ();        int n = grid[0].size ();                int dp[m][n];        Dp[0][0] = grid[0][0];        for (int i = 1; i < m; ++i)             dp[i][0] = dp[i-1][0] + grid[i][0];         for (int i = 1; i < n; ++i)            dp[0][i] = dp[0][i-1] + grid[0][i];         for (int i = 1;i<m;++m) for            (int j = 1; j<n;++n)                 dp[i][j] = min (dp[i-1][j],dp[i][j-1]) + grid[i][j];                return dp[m-1][n-1];}    ;

You see, this requires m*n space, in fact, we do not need to maintain the entire m*n, just to ensure that the outermost row and a column is good.

Class Solution {public:    int minpathsum (vector<vector<int>>& grid) {        int m = grid. Size ();        int n = grid[0].size ();                int dp[m],hr[n];        Dp[0] = hr[0] = grid[0][0];        for (int i = 1; i < m; ++i)             dp[i] = dp[i-1] + grid[i][0];         for (int i = 1; i < n; ++i) {            hr[i] = hr[i-1] + grid[0][i];         }        Update horizontal line every time for next use        int tmp;        for (int i = 1;i<m;++i) {            hr[0] = dp[i];            for (int j=1;j<n;++j) {                Hr[j] = min (hr[j-1],hr[j]) + grid[i][j];              }        }        return hr[n-1];}    ;

Does space have an effect on time?

[LC] 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.