Link: https://oj.leetcode.com/problems/unique-paths-ii/
Approach I: DP with O(n^2) space complexity
public class Solution {
//DP with O(n_2)
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] matrix = new int [m][n];
//initialize the first col
for(int i = 0; i < m; i++){
if(obstacleGrid[i][0] == 0){
matrix[i][0] = 1;
}
else break;//if there is an obstacle in [i][0], then all elements belowin 1st col = 0
}
//initialize the first row
for(int j = 0; j < n; j++){
if(obstacleGrid[0][j] == 0){
matrix[0][j] = 1;//if there is an obstacle in [0][j], then all elements after in 1st row = 0
}
else break;
}
for(int i = 1; i < m; i++){
for(int j =1; j < n;j++){
if(obstacleGrid[i][j] == 1){
matrix[i][j] = 0;
}
else{
matrix[i][j] = matrix[i-1][j]+matrix[i][j-1];
}
}
}
return matrix[m-1][n-1];
}
}
Approach II: DP with O(n) space complexity
虽然我们只用了一个行向量存储。但实际上每次循环i的时候,res[j] 都代表result[i][j].
在程序的else中,我们看到,如果j==0, 即第0列的元素的值是不改变的。If result[i-1][j] ==0, then result[i][j] == 0; If result[i-1][j] ==1, then result[i][j] == 1.
即每次i循环得到的res[j] 都和上一次循环 (i-1)时候的相等。
举例:如果obstacleGrid如左图所示,则res如右图所示。右图每一行代表一个循环i下的res。
public class Solution {
//DP with O(n)
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[] res = new int [n];
//initialize the first col
res[0] = 1;
for(int i = 0; i < m; i++){
for(int j =0; j < n;j++){
if(obstacleGrid[i][j] == 1){
res[j] = 0;
}
else{
//if j = 0 (1st col), then res[j] is not updated. i.e. the element on i-th row = element on (i-1)-th row
//if res[j]==1, this row's res[j]==1;
//if res[j]==0, this row's res[j]==0.
if(j >0){
res[j] = res[j] + res[j-1];
}
}
}
}
return res[n-1];
}
}
Approach III: Since there are blocks, we cannot use Combinatoric Math.