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?
Note: m and n will be at most 100.
Example 1:
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
方法一:递归
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m==1 and n>=1:
return 1
elif n==1 and m>=1:
return 1
else:
return self.uniquePaths(m-1,n)+self.uniquePaths(m,n-1)
这段代码无法通过LeetCode,递归太深了改用方法二
方法二:动态规划(我也不知道算不算动态规划hiahia)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
func = self.outer(m,n)
return func
def outer(self,m,n):
UP=[[0]*(n+1) for i in range(m+1)]
def calculate(a,b):
if a==1 and b>=1:
return 1
elif b==1 and a>=1:
return 1
elif UP[a][b]!=0:
return UP[a][b]
else:
UP[a][b] = calculate(a-1,b)+calculate(a,b-1)
return UP[a][b]
return calculate(m,n)