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