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?
There are two ways of solving this problem.
1. Direct mathematical expression Choose M-1 from M+n-2
Class solution: # @return An integer def FAC (self,n): if N==1 or n==0: return 1 return N*SELF.FAC ( n-1) def uniquepaths (self, M, n): if M==1 or n==1: return 1 val1=self.fac (m+n-2) VAL2=SELF.FAC ( m-1) Val3=self.fac (n-1) result=val1/(VAL2*VAL3) return result
2. Dynamic planning, each step is adjacent to the nearest lattice and.
The code is as follows
Class solution: # @return An integer def uniquepaths (self, M, n): dp=[[0 for index in range (n)] for index in R Ange (m)] for row in range (m): dp[row][0]=1 for Col in Range (n): dp[0][col]=1 for row in range (1,m): For col in Range (1,n): dp[row][col]=dp[row-1][col]+dp[row][col-1] return dp[m-1][n-1]
The Unique Path leetcode Python