Daily LeetCode 62. Unique Paths

https://leetcode.com/problems/unique-paths/

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?

img
Above is a 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

1
2
3
4
5
6
7
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:

1
2
Input: m = 7, n = 3
Output: 28

思路及代码:

给定一个m x n的方格,起点为左上角,终点为右下角,每次能够向下或者向右走一格,要求求出所有可能的路径数。

这是一题典型的运用动态规划解决的问题,我们可以设置一个二维数组dp[i][j],表示当前方格到终点的路径条数,以3 x 2的方格为例,这种情况下dp数组如下:
$$
dp=\left[
\begin{array}{ccc}
3&2&1\
1&1&0
\end{array}
\right]
$$
在代码编写中,我们要从终点向起点走,将dp数组的最后一列和最后一行设置为1,因为从这些方格出发到终点只有一条路径。在遍历过程中按照dp[i][j] = dp[i][j+1] + dp[i+1][j]更新数组,最终dp[0][0]就是路径数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m == 1 and n == 1:
return 1
dp = [[0] * m for _ in range(n)]
dp[n - 1][m - 1] = 0
for i in range(m - 1):
dp[n - 1][i] = 1
for i in range(n - 1):
dp[i][m - 1] = 1

for i in range(n - 1, 0, -1):
for j in range(m - 1, 0, -1):
dp[i - 1][j - 1] = dp[i][j - 1] + dp[i - 1][j]

return dp[0][0]