跳至主要內容

62. Unique Paths


62. Unique Pathsopen in new window

🟠   🔖  数学 动态规划 组合数学  🔗 LeetCodeopen in new window

题目

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 10^9.

Example 1:

Input: m = 3, n = 7

Output: 28

Example 2:

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 -> Down -> Down

  2. Down -> Down -> Right

  3. Down -> Right -> Down

Constraints:

  • 1 <= m, n <= 100

题目大意

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。问总共有多少条不同的路径?

解题思路

可以使用动态规划来解决问题,机器人到达每个格子的路径数如下所示:

❤️111111
1234567
13610152128
  1. 动态规划:定义一个二维数组 dp,其中 dp[i][j] 表示从 (0, 0)(i, j) 的不同路径数目。

  2. 状态转移方程:从 (0, 0)(i, j) 的路径有两条:从 (i-1, j) 向下移动和从 (i, j-1) 向右移动,到达 (i, j) 的路径数就是上方格子 (i-1, j) 和左边格子 (i, j-1) 的路径数之和。状态转移方程为 dp[i][j] = dp[i-1][j] + dp[i][j-1]

  3. 边界条件:对于第一行和第一列,由于它们只能从上方或左侧移动到达,所以路径数目都是 1。

  4. 初始化:初始化第一行和第一列的路径数目。

  • 时间复杂度: O(m * n) - 遍历整个二维数组。
  • 空间复杂度: O(m * n) - 使用了一个二维数组来存储中间状态。可以优化为 O(n),只需使用一维数组来存储当前行的状态。

代码

动态规划
// 时间复杂度 O(m * n),空间复杂度 O(m * n)
/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var uniquePaths = function (m, n) {
	const dp = new Array(m).fill(1).map(() => new Array(n).fill(1));
	for (let i = 1; i < m; i++) {
		for (let j = 1; j < n; j++) {
			dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
		}
	}
	return dp[m - 1][n - 1];
};

相关题目

相关题目
- [63. 不同路径 II](./0063.md)
- [64. 最小路径和](./0064.md)
- [174. 地下城游戏](https://leetcode.com/problems/dungeon-game)
- [2304. 网格中的最小路径代价](https://leetcode.com/problems/minimum-path-cost-in-a-grid)
- [2087. 网格图中机器人回家的最小代价](https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid)
- [2400. 恰好移动 k 步到达某一位置的方法数目](https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps)
- [2435. 矩阵中和能被 K 整除的路径](https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k)