题目
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?
链接:https://leetcode.com/problems/unique-paths/
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?
Example:
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
思路及代码
DP
- path[i][j]:到达i行j列的方法数
- path[i][j] = path[i-1][j] + path[i][j-1],到达i行j列可以从上方格往下走,也可以从左方格往右走
- 初始值 path[i][0] = 1, path[0][j] = 1:所有第一行和第一列的格子都是1
- 返回path[n][m]
# 28ms 78.24%
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
path = [[0]*m]*n
for i in range(n):
path[i][0] = 1
for j in range(m):
path[0][j] = 1
for i in range(1, n):
for j in range(1, m):
path[i][j] = path[i-1][j] + path[i][j-1]
return path[n-1][m-1]
复杂度
T =
O
(
m
∗
n
)
O(m*n)
O(m∗n)
S =
O
(
m
∗
n
)
O(m*n)
O(m∗n)