10.3 Unique Path II

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. 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值