难度: Medium
原题连接
内容描述
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
Example 2:
Input: m = 7, n = 3
Output: 28
思路 1 - 时间复杂度: O(m * n)- 空间复杂度: O(m * n)******
1 | 1 | 1 |
1 | 2 | 3 |
1 | 3 | 6 |
1 | 4 | 10 |
1 | 5 | 15 |
1 | 6 | 21 |
1 | 7 | 28 |
dp[i][j]代表的是走到点(i, j)有多少种path
beats 99.08%
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m < 1 or n < 1:
return 0
dp = [[1] * n for i in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
思路 2 - 时间复杂度: O(m * n)- 空间复杂度: O(n)******
根据上面的表格,我们可以看出规律,每一行的下一行都是它自身的前缀和数组
这样我们可以将空间降到O(n),先固定初始行的值,全为1,然后开始循环计算剩下的m-1次
beats 99.08%
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m < 1 or n < 1:
return 0
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j-1]
return dp[n-1]
思路 3 - 时间复杂度: O(m + n)- 空间复杂度: O(1)******
这道题我一看到就觉得这不就是排列组合吗,一共走m+n-2步, 其中m-1步是向右边走,所以不就是从m+n-2中选m-1个的问题吗,阶乘问题,so easy! 妈妈
再也不用担心我的学习!!这个方法beats 99.97%
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def factorial(num):
res = 1
for i in range(1, num+1):
res *= i
return res
return factorial(m+n-2) / factorial(n-1) / factorial(m-1)
另外补充一句,我发现math模块里面自带factorial函数,只要import math之后调用即可,