Leetcode "Unique Paths" Python implementation

Source: Internet
Author: User

title :

A robot is located at the Top-left corner of a m x n grid (marked ' Start ' in the diagram 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 diagram below).

How many possible unique paths is there?

Above is a 3 x 7 grid. How many possible unique paths is there?

Note: m and N would be is at most 100.

code : OJ Test via runtime:44 ms

1 classSolution:2     #@return An integer3     defuniquepaths (self, M, N):4         #None case5         ifM < 1orN < 1:6             return07         #Special Case8         ifM==1orN==1 :9             return1Ten          One         #Deep first matrix ADP = [[0 forColinchRange (n)] forRowinchrange (m)] -         #The elements in Frist row has only one avaialbe Pre-node -          forIinchrange (n): theDp[0][i]=1 -         #The elements in first column has only one avaialble pre-node -          forIinchRange (m): -Dp[i][0]=1 +         #iterator other elements in the 2d-matrix -          forRowinchRange (1, m): +              forAo.inchRange (1, N): ADp[row][col]=dp[row-1][col]+dp[row][col-1] at          -         returnDP[M-1][N-1]

Ideas :

Dynamic programming of classic topics, using iterative methods to solve.

1. Handle the None case and special case first

2. The elements on the first and first columns of the 2d-matrix can only be reached from the elements above or to the left, so that their values are directly obtained

3. Traverse the rest of the positions: each position can only be reached by its left or upper element, thus iterating the formula DP[ROW][COL]=DP[ROW-1][COL]+DP[ROW][COL-1]

4. The DP matrix stores all possible passes from the location to the current position after the traversal is complete, so returning dp[m-1][n-1] is the desired value

Leetcode "Unique Paths" Python implementation

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.