1. 程式人生 > >LeetCode Unique Paths II

LeetCode Unique Paths II

是的進階版題目。思路與Unique Paths相似,不同點在於加了障礙物,DP的更新當前點方式有所不同, 若是此處有障礙物,res裡這一點就是0,若此處沒有障礙物,res裡這一點就同行上一列和同列上一行的和。

Note:初始化是點res[0][0].

AC Java:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0){
            return 0;
        }
        int h = obstacleGrid.length;
        int w = obstacleGrid[0].length;
        int[][] res = new int[h][w];
        
        res[0][0] = obstacleGrid[0][0] == 1 ? 0:1; //error
        
        for(int i = 1; i < h; i++){
            res[i][0] = obstacleGrid[i][0] == 1 ? 0:res[i-1][0];
        }
        for(int i = 1; i < w; i++){
            res[0][i] = obstacleGrid[0][i] == 1 ? 0:res[0][i-1];
        }
        for(int i = 1; i < h; i++){
            for(int j = 1; j < w; j++){
                res[i][j] = obstacleGrid[i][j] == 1 ? 0:res[i-1][j] + res[i][j-1];
            }
        }
        return res[h-1][w-1];
    }
}

對應的本題也有像Unique Paths一般的降維儲存歷史資訊的方法。

Note:更新時這裡j是從0開始與Unique Paths不同,還有用res[j-1]前要確保j>0.

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        //Method 2
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length ==0){
            return 0;
        }
        int h = obstacleGrid.length;
        int w = obstacleGrid[0].length;
        int [] res = new int[w];
        res[0] = obstacleGrid[0][0] == 1 ? 0 : 1;
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){     //error
                if(obstacleGrid[i][j] == 1){
                    res[j] = 0;
                }else{
                    if(j>0){                //error
                        res[j] += res[j-1];
                    }
                }
                
            }
        }
        return res[w-1];
    }
}