Q63 Unique Paths II
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 are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways
to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Input: m = 7, n = 3
Output: 28
dp[n][m] = dp[n][m-1] + dp[n-1][m]
。注意,如果 n 或 m 有一个值为 1,则结果为 1。【注】C(N, M) = N! / (M! * (N-M)!)
两种方法的代码见Python实现部分。
class Solution:
# DP
# Time: O(n^2)
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[1 for col in range(m)] for row in range(n)] # n行m列的数组
if m == 1 or n == 1:
return 1
for i in range(1, n):
for j in range(1, m):
dp[i][j] = dp[i][j-1] + dp[i-1][j]
return dp[i][j]
# Math
# C(m+n-2, m-1) or C(m+n-2, n-1)
# C(N, M) = N!/(M!*(N-M)!)
# Time: O(n)
def uniquePaths2(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return self.calFactorial(m+n-2) // self.calFactorial(m-1) // self.calFactorial(n-1)
def calFactorial(self, num):
if num <= 1:
return 1
return num * self.calFactorial(num - 1)
m = 3
n = 7
print(Solution().uniquePaths(1, 1)) # 1
print(Solution().uniquePaths(m, n)) # 28
print(Solution().uniquePaths2(m, n)) # 28