Minimum Path Sum

Source: Internet
Author: User

https://leetcode.com/problems/minimum-path-sum/

The main idea: give a m*n table, which stores a m*n non-negative integer, in the upper left corner of the path to the lower right corner (requires only one step down or to the right), to find out the path of the smallest number of numbers.

Problem-solving ideas: using F[I][J] to indicate from the origin to the first row of the J column of the smallest sum, then f[i][j] The previous step is either f[i][j-1], or f[i-1][j], select the minimum value and the step itself to add the number, you can get f[i][j]. But note that the boundary of the table should be handled in a special way, with only one direction to go.

As can be seen from the above, the problem is a typical dynamic programming.

The code is as follows:

1 classSolution {2  Public:3     intMinpathsum (vector<vector<int> >&grid) {4         introw =grid.size ();5         intCol = grid[0].size ();6         if(Row = =0)return 0;7 8         intF[row][col];9          for(inti =0; i < row; i++)Ten         { One              for(intj =0; J < Col; J + +) A             { -F[I][J] =Grid[i][j]; -             } the         } -          for(inti =0; i < row; i++) -         { -              for(intj =0; J < Col; J + +) +             { -                 if(I >=1&& J >=1) +                 { AF[I][J] + = min (f[i-1][J], f[i][j-1]); at                 } -                 Else if(I >=1) F[i][j] + = f[i-1][j]; -                 Else if(J >=1) F[i][j] + = f[i][j-1]; -             } -         } -         returnf[row-1][col-1]; in     } -};

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.