LeetCode Unique Paths
Solving LeetCode with Unique Paths
Original question
The number of different paths from the start point to the end point of a robot can only go to the right or down.
Note:
The maximum grid size is 100*100.
Example:
Input: m = 3, n = 7
Output: 28
Solutions
A common primary school student's Mathematical Olympiad problem can be solved by means of permutation and combination. A total of steps (S-1) + (n-1) should be taken, m-1) steps down, (n-1) to the right, and there is a formulamCn = n!/m!(n-m)!, You can use the following code to solve the problem:
import mathclass Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ m -= 1 n -= 1 return math.factorial(m+n) / (math.factorial(n) * math.factorial(m))
Of course, a more common approach is dynamic planning. To reach a grid, you only need to come over from the grid above it or on the left. Recursive relationship:dp[i][j]=dp[i-1][j]+dp[i][j-1]. The initialization condition is that there is only one path on the left and the top, and all grids are initialized to 1 during initialization.
AC Source Code
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [[1 for __ in range(n)] for __ in range(m)] for i in range(1, n): for j in range(1, m): dp[j][i] = dp[j - 1][i] + dp[j][i - 1] return dp[m - 1][n - 1]if __name__ == "__main__": assert Solution().uniquePaths(3, 7) == 28