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]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
本题是unique paths的follow up
unique paths的题意简单来说 是从一个m*n的矩阵的左上角走到右下角 只能向右或向下 有多少种走法
比如输入m=3,n=3 也就是3*3的矩阵
[
[0,0,0],
[0,0,0],
[0,0,0]
]
对于右下角的终点 也就是(2,2) 到达他有两种方式 从他的上方的(1,2) 和左方(2,1)
用T(m,n)表示到达(m,n)点的走法 那么可以得到T(m,n) = T(m-1,n) + T(m,n-1)
用dp求解就可以了
class Solution {
int uniquePaths(int m, int n) {
vector<vector<int> > path(m, vector<int> (n, 1));
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
path[i][j] = path[i - 1][j] + path[i][j - 1];
return path[m - 1][n - 1];
}
};
本题增加了障碍的概念 其实只是多了一种判断
今天重写了一下 用了两个长度为n的数组存储计算结果
看了一年之前的代码 用的是m*n的数组存储临时计算结果
比较之下 代码简洁了很多
但是看了discuss 还有用一个长度为n的数组解决的 代码也相当简洁
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int width = obstacleGrid[0].length;
int[] dp = new int[width];
dp[0] = 1;
for (int[] row : obstacleGrid) {
for (int j = 0; j < width; j++) {
if (row[j] == 1)
dp[j] = 0;
else if (j > 0)
dp[j] += dp[j - 1];//1.
}
}
return dp[width - 1];
}
1.如果我们暂时忽略障碍 那么
如果用m*n的数组存储计算结果 最优子结构应该是 dp[i][j] = dp[i-1][j]+dp[i][j-1]
因为我们每次计算只用到了上一行和本行 所以可以优化为 仅使用两个长度为n的数组存储计算结果 那么表达式应该是 newLine[i] = oldLine[i] + newLine[i-1]
其实我们还可以把两个数组进行合并 用一个长度为n的数组存储计算结果 那么表达式应该是
dp[i] = dp[i] + dp[i-1]
等号左边dp[i]表示我们要求的 等号右边等同于oldLine[i] + newLine[i-1]