1 """
2 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
3 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).
4 How many possible unique paths are there?
5 Above is a 7 x 3 grid. How many possible unique paths are there?
6 Note: m and n will be at most 100.
7 Example 1:
8 Input: m = 3, n = 2
9 Output: 3
10 Explanation:
11 From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
12 1. Right -> Right -> Down
13 2. Right -> Down -> Right
14 3. Down -> Right -> Right
15 Example 2:
16 Input: m = 7, n = 3
17 Output: 28
18 """
19 """
20 看见这个题,我找了个规律,用了递归
21 但对于数据量大时 会超时
22 Time Limit Exceeded
23 Last executed input
24 23
25 12
26 -------------------------------------------------
27 以下为手动计算
28 1 1 1 1
29 1 2 3 4
30 1 3 6 10
31 paths[i, j] == paths[i-1, j] + paths[i, j-1]
32 """
33 class Solution1:
34 def uniquePaths(self, m, n):
35 if m == 1 or n == 1:
36 return 1
37 else:
38 return self.uniquePaths(m-1, n)+self.uniquePaths(m, n-1)
39
40 """
41 解法二可以用空间换时间,建立一个二维数组
42 数组的[-1,-1]就是路径数
43 """
44 class Solution2:
45 def uniquePaths(self, m, n):
46 dp = [[1]*m for _ in range(n)] #n行 m列的初始化为1的矩阵
47 for i in range(1, n):
48 for j in range(1, m):
49 dp[i][j] = dp[i-1][j] + dp[i][j-1]
50 return dp[-1][-1]
51
52 """
53 解法三用了一定数学基础
54 设向下走是1,向右走是0,
55 原问题变成m-1个0与n-1个1有多少种不同的排列,高中数学
56 思考在 (m-1)+(n-1)个位置里放m-1个0,其余n-1个位置自动为1
57 就是(m+n-2)!//((m-1)!*(n-1)!)
58 """
59 class Solution3:
60 def uniquePaths(self, m, n):
61 t = 1
62 for i in range(1, n): #!!!bug因为(1,n)实际就是(n-1)!
63 t = t * i
64 e = 1
65 for i in range(m, m+n-1):#这里是(m+n-2)!//(m-1)!
66 e = e * i
67 return e // t #这里即为(m+n-2)!//((m-1)!*(n-1)!)