[Leetcode] unique paths & unique paths II & minimum path sum (matrix DP for Dynamic Planning)

Source: Internet
Author: User

Unique paths

Https://oj.leetcode.com/problems/unique-paths/

A robot is located at the top-left corner ofMXNGrid (marked 'start' in the dimo-below ).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'finish 'in the dimo-below ).

How many possible unique paths are there?

Above is a 3x7 grid. How many possible unique paths are there?

Note: MAndNWill be at most 100.

My ideas

I personally like this kind of problem, called the matrix DP problem, which obviously requires dynamic planning. Generally, this kind of matrix DP problem requires the following attention:

State: F [x] [Y] indicates that I go from the starting point to the coordinates x, y ......
Function: The last step
Intialize: Start Point
Answer: End Point

Let's first look at the State, which can be defined in this way,F [x] [Y] indicates that the unique paths (X, Y) is obtained from the starting point (0, 0 )..

Let's look at how to find the state transition equation. It is not difficult to find that the unique paths at the point (x, y) starting from the starting point is actually equalUnique paths from the starting point to the left of the point (that is, (x, Y-1)AddThe unique paths of a point (x-1, Y) above the point starting fromAnd.

Obviously, the initialization of the F matrix sets the leftmost column and the top row to 1, because the starting point is to go down or to the right, the unique paths of each point in the column or row is 1. Note that even if the start position is equal to the finish position (that is, there is only one point ), its unique paths is also 1 (you can calculate it by yourself ).

The following is the AC code on leetcode:

/** * Zhou J */ class Solution {public:    int uniquePaths(int m, int n)     {        if (m == 0 || n == 0) {            return 0;        }                int sum[m][n];                for (int i = 0; i < m; i++) {            sum[i][0] = 1;        }                for (int i = 0; i < n; i++) {            sum[0][i] = 1;        }                for (int i = 1; i < m; i++) {            for (int j = 1; j < n; j++) {                sum[i][j] = sum[i - 1][j] + sum[i][j - 1];            }        }                return sum[m - 1][n - 1];    }};

If you understand the above question, you can refer to the following follow question.

Follow question
Unique paths II

Https://oj.leetcode.com/problems/unique-paths-ii/

Follow up for "unique paths ":

Now consider if some obstacles are added to the grids. How many unique paths wocould there be?

An obstacle and empty space is marked1And0Respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as partitioned strated below.

[  [0,0,0],  [0,1,0],  [0,0,0]]

The total number of unique paths is2.

Note: MAndNWill be at most 100.

The following is my AC code:

/** * Zhou J */ class Solution {public:    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {        if (obstacleGrid.size() == 0)        {            return 0;        }                int numOfRows = obstacleGrid.size();        int numOfCols = obstacleGrid[0].size();        vector<vector<int>> sum(obstacleGrid);                // initialize the left column        for (size_t ix = 0; ix != numOfRows; ++ix)        {            if (obstacleGrid[ix][0] == 0)            {                sum[ix][0] = 1;            }            else            {                for (size_t newIx = ix; newIx != numOfRows; ++newIx)                {                    sum[newIx][0] = 0;                }                break;                             }                // initialize the top row        for (size_t ix = 0; ix != numOfCols; ++ix)        {            if (obstacleGrid[0][ix]  == 0)            {                sum[0][ix] = 1;            }            else            {                for (size_t newIx = ix; newIx != numOfCols; ++newIx)                {                    sum[0][newIx] = 0;                }                break;            }        }                // switch the state        for (size_t i = 1; i != numOfRows; ++i)        {            for (size_t j = 1; j != numOfCols; ++j)            {                if (obstacleGrid[i][j] == 0)                {                    sum[i][j] = sum[i-1][j] + sum[i][j-1];                }                else                {                    sum[i][j] = 0;                }                            }        }                // return the answer        return sum[numOfRows - 1][numOfCols - 1];    }};

In contrast to the previous question, there are two points of attention:

1. when initializing rows and columns, if a certain point is an obstacle, not only will the sum corresponding to this position be set to 0, however, the sum corresponding to each of the following positions must be set to 0. It is easy to understand that a row or column belongs to a straight line, as long as there is an obstacle, the entire line will be deprecated.

2. In the process of state transfer, if an obstacle is encountered, the change point should return 0 directly.

Minimum path sum

Let's take a look at the problems related to matrix DP as follows:

Minimum path sum

Https://oj.leetcode.com/problems/minimum-path-sum/

GivenMXNGrid filled with non-negative numbers, find a path from top left to bottom right whichMinimizesThe sum of all numbers along its path.

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

This question is actually a routine with the above two questions, but the State Matrix sum here stores the shortest path and. The shortest path to a certain position starting from the starting point must be the shortest path to the left or above of the position starting from the starting point (the two are smaller) plus the path of the position itself.

State: F [x] [Y] shortest path from the start point to X and Y
Function: F [x] [Y] = min (F [x-1] [Y], F [x] [Y-1]) + cost [x] [Y]
Intialize: F [0] [0] = cost [0] [0]
F [I] [0] = sum (0, 0-> I, 0)
F [0] [I] = sum (0, 0-> 0, I)
Answer: F [n-1] m-1]

The following is the AC code:

/** * Zhou J */class Solution {public:    int minPathSum(vector<vector<int> > &grid)     {        if (grid.size() == 0)        {            return 0;        }                int numOfRows = grid.size();        int numOfCols = grid[0].size();        vector<vector<int>> sum(grid);                sum[0][0] = grid[0][0];                // initialize the left column        for (size_t ix = 1; ix != numOfRows; ++ix)        {            sum[ix][0] = sum[ix - 1][0] + grid[ix][0];        }                // initialize the top row        for (size_t ix = 1; ix != numOfCols; ++ix)        {            sum[0][ix] = sum[0][ix - 1] + grid[0][ix];        }                // switch the state        for (size_t i = 1; i != numOfRows; ++i)        {            for (size_t j = 1; j != numOfCols; ++j)            {                sum[i][j] = min(sum[i][j - 1], sum[i - 1][j]) + grid[i][j];            }        }                // return the minimum path sum        return sum[numOfRows - 1][numOfCols - 1];            }};
Tips

Leetcode is a very good platform. When we are doing the above questions, we must first think about it, do not rush to Google Answers, if your code is not AC, leetcode will display testcase that cannot be used to you. Based on these prompts, we will correct the answer step by step and often get a good workout.

I personally think that the dynamic planning problem like matrix DP is usually the simplest. For such questions, initialize is usually the row and column corresponding to the initialization Start Point. In subsequent articles, I will further analyze the dynamic planning problems involved in some interview questions in North America.

I still have a master's degree in China, but I have worked with some friends who are still working in China but want to work in the bay area in the future. One problem is that if I change jobs frequently, will interviews in North America be affected? The answer is yes. I consulted a Facebook interviewer. He meant that intern often changes jobs, but fulltime often changes jobs, which has a huge impact. For example, intern is equivalent to a girlfriend. In this society, we are still allowed to change our girlfriends (it is a little awkward), but fulltime is equivalent to wife, you cannot get divorced all the time, right ?!

PS: How do I want to work in the Bay Area? Please push it internally ~!!

[Leetcode] unique paths & unique paths II & minimum path sum (matrix DP for Dynamic Planning)

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.