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?
①很直观的递归公式f(m,n)=f(m-1,n)+f(m,n-1).可以看到中间有重复的计算f(m-1,m-1).遇到递归有重复计算可以考虑用动态规划,或者备忘录来解决。备忘录还要用到递归,因而最好还是选用动态规划。
②本题动态转移方程比较直观,设为dp[m][n]=dp[m][n-1]+dp[m-1][n];考虑优化存储空间。可以看到在求下一次m的时候即dp[m][k]只用到dp[m-1][k]和本次的dp[m][k-1]因而,只需用一维数组即可;
③到计算dp[m][k]时,数组保存的就是dp[m-1][k-1]的数据变为dp[n]=dp[n]+dp[n-1];由于dp[n-1]用的是本次计算的结果,故而计算顺序为从前到后。
public int uniquePaths(int m, int n) {
if (m > n)
return uniquePaths(n, m);
if (m == 1)
return 1;
int[] dp = new int[n + 1];
Arrays.fill(dp, 1);
for (int i = 1; i < m; ++i) {
for (int j = 2; j <= n; ++j) {
dp[j] += dp[j - 1];
}
}
return dp[n];
}
63 Unique Paths II
Follow up for “Unique Paths”:
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
// 本题目和上一题目的区别在于初始化的时候有差别,遇到障碍物则后面的均为0;之后在计算时遇到障碍物直接置结果为0,同时列的第一个元素需要同第一行一样考虑下;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null) {
return 0;
}
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[] dp = new int[n];
if (obstacleGrid[0][0] != 1) {
dp[0] = 1;
}
for (int i = 1; i < n; ++i) {
if (obstacleGrid[0][i] == 1) {
dp[i] = 0;
} else {
dp[i] += dp[i - 1];
}
}
for (int i = 1; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (obstacleGrid[i][j] == 1) {
dp[j] = 0;
} else {
//若为第一个元素并且不是1,则和上次计算结果一致;若不是第一个元素,则直接计算
if (j != 0) {
dp[j] += dp[j - 1];
}
}
}
}
return dp[n - 1];
}