题目

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?
image.png
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
  2. Output: 3
  3. Explanation:
  4. From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
  5. 1. Right -> Right -> Down
  6. 2. Right -> Down -> Right
  7. 3. Down -> Right -> Right

Example 2:

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

题意

在矩形中找到一条路径,起点为左上顶点,终点为右下顶点,路径中只能向右或向下走,要求统计不同路径的个数。

思路

组合数:因为每次只能向右或向下走,所以符合条件的路径的长度必然是 m+n-2,其中有 m-1 个点是向右走,n-1 个点是向下走,问题就转化为了在 m+n-2 个点中找出 m-1 个点(或找出 n-1 个点,都一样),求0062. Unique Paths (M) - 图2的值。
组合数求值可以用公式:0062. Unique Paths (M) - 图3,也可以用递推公式计算:0062. Unique Paths (M) - 图4

动态规划:dp[i][j]记录可以到达位置(i, j)的路径的数目,因为(i, j)只可能从(i, j-1)向右走到达,或者从(i-1, j)向下走到达,所以有0062. Unique Paths (M) - 图5
注意到dp[i][j]只与左边和上边的dp有关,且我们的目标只是为了得到最后一行最后一列的dp,所以可以用滚动数组对上述过程进行空间优化,无需使用二维数组。


代码实现

Java

组合数

  1. public int uniquePaths(int m, int n) {
  2. return calculate(m + n - 2, m - 1);
  3. }
  4. private int calculate(int n, int m) {
  5. double ans = 1.0;
  6. while (m >= 1) {
  7. ans *= 1.0 * n-- / m--;
  8. }
  9. return (int) Math.round(ans);
  10. }

动态规划

  1. class Solution {
  2. public int uniquePaths(int m, int n) {
  3. int[][] dp = new int[n][m];
  4. dp[0][0] = 1;
  5. for (int i = 0; i < n; i++) {
  6. for (int j = 0; j < m; j++) {
  7. if (i != 0 || j != 0) {
  8. dp[i][j] = findDP(dp, i - 1, j) + findDP(dp, i, j - 1);
  9. }
  10. }
  11. }
  12. return dp[n - 1][m - 1];
  13. }
  14. private int findDP(int[][] dp, int i, int j) {
  15. if (i < 0 || j < 0) {
  16. return 0;
  17. }
  18. return dp[i][j];
  19. }
  20. }

滚动数组优化

class Solution {
    public int uniquePaths(int m, int n) {
        int[] dp = new int[m];
        dp[0] = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[j] = dp[j] + (j > 0 ? dp[j - 1] : 0);
            }
        }
        return dp[m - 1];
    }
}

JavaScript

/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var uniquePaths = function (m, n) {
  let scroll = new Array(m).fill(1)
  for (let i = 1; i < n; i++) {
    for (let j = 0; j < m; j++) {
      scroll[j] = j === 0 ? scroll[j] : scroll[j] + scroll[j - 1]
    }
  }
  return scroll[m - 1]
}