62. Unique Paths
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 = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
Constraints:
1 <= m, n <= 100
It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
1 动态规划解法
动态规划主要是找到跟上一条记录联系的公式,这里的公式就是path[i][j] = path[i-1][j] + path[i][j-1]。可以看下面的图,
-
往下走的列path[i][0]都初始化为1,表示一直往下有一种的解法;往右走的行path[0][j]都初始化为1,表示一直往右有一种的解法。
-
再看第二列,当前位置的记录是由上面的解法,和左边的解法,加起来就是当前的解法。所以 2 = 1 + 1, 3 = 2 + 1. 以此类推。
-
结果是path[m-1][n-1], 因为是从0开始计算的。
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0 ; i < m; i++) {
dp[i][0] = 1;
}
for (int k = 0; k < n; k++) {
dp[0][k] = 1;
}
for (int i = 1; i < m; i++) {
for (int k = 1; k < n; k++) {
dp[i][k] = dp[i - 1][k] + dp[i][k - 1];
}
}
return dp[m - 1][n - 1];
}
2 二项系数解法Binomial coefficient
数学公式的解法,实际上先考虑一共要走多少步。比如Input: m = 7, n = 3,实际上是 m- 1 + n -1, 也就是8步。这就是表示有8个空要等着填。那么有多少种填发呢,比如往下走表示D,往右走表示R,因为二项系数解法,大小都是一样的,为了效率,用小的来解比较快。比如有2个R, 由于 (n - 1)。那么第一个R可以放任意8个位置中的一个,第二个R可以放任意7个位置中的一个。因为左边(1, 2)和 (2, 1),都是放R的话是一样的,所以就要除以二项系数的当前系数。
class Solution {
public int uniquePaths(int m, int n) {
int totalStep = m + n - 2;
int change = (m > n ? n : m) - 1;
double count = 1;
for (int i = 1; i <= change; i++) {
count = count * totalStep / i;
totalStep--;
}
return (int)count;
}
}
参考
https://www.youtube.com/watch?v=M8BYckxI8_U
https://leetcode.com/problems/unique-paths/