Leetcode | | 64. Minimum Path Sum

Source: Internet
Author: User

Problem:

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.

Hide TagsArray Dynamic ProgrammingTest instructions: Looking for a weighted minimum path from the top left of the matrix to the bottom right

Thinking:

(1) The path problem of the matrix (the total number of paths, the total number of paths with obstacles, the weighted minimum, the maximum path, etc.), because of the clear and simple State transfer formula,
All can be solved by DP method, the time complexity is O (m*n)

(2) solve the global optimal problem with DP!! Whether the problem has local optimal solution, State transfer formula: A[i][j] = min (A[i-1][j], a[i][j-1]) + grid[i][j];

The choice of each step is defined as the optimal solution, so the local optimization is established

Code

Class Solution {public:    int minpathsum (vector<vector<int> > &grid) {        vector<vector<int > >::const_iterator con_it=grid.begin ();        int m=grid.size ();        int n= (*CON_IT). Size ();        vector<int> tmp (n,0);        Vector<vector<int> > A (m,tmp);        if (m==0 | | n==0)            return 0;        A[0][0]=GRID[0][0];        for (int i=1;i<m;i++)           a[i][0]=a[i-1][0]+grid[i][0];        for (int j=1;j<n;j++)            a[0][j]=a[0][j-1]+grid[0][j];        for (int i = 1; i < m; i++)            for (int j = 1; j < N; j + +)                a[i][j] = min (A[i-1][j], a[i][j-1]) + Grid[i][j];
   return a[m-1][n-1];    };


Leetcode | | 64. 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.