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?
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 | Input: m = 3, n = 2 |
Example 2:
1 | Input: m = 7, n = 3 |
思路及代码:
给定一个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 | class Solution: |