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?
Example 1:
Input:m = 3, n = 2Output:3Explanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:1. Right -> Right -> Down2. Right -> Down -> Right3. Down -> Right -> Right
Example 2:
Input:m = 7, n = 3Output:28
Constraints:
1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
动态规划:
class Solution {
public int uniquePaths(int _m, int _n) {
int n = Math.min(_m, _n);
int m = Math.max(_m, _n);
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j == 0) {
dp[j] = dp[j];
} else if (i == 0) {
dp[j] = dp[j - 1];
} else {
dp[j] += dp[j - 1];
}
}
}
return dp[n - 1];
}
}
数学方法:
机器人总共移动的次数 S=m+n-2,向下移动的次数 D=m-1,那么问题可以看成从 S 中取出 D 个位置的组合数量,这个问题的解为 C(S, D)。(参考https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.md#%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97)
class Solution {
public int uniquePaths(int m, int n) {
int S = m + n - 2; // 总共的移动次数
int D = m - 1; // 向下的移动次数
long ret = 1;
for (int i = 1; i <= D; i++) {
ret = ret * (S - D + i) / i; // 这里注意不能写成 ret *= (S - D + i) / i;,这样会导致除不尽而出错
}
return (int) ret;
}
}