leetCode-Unique Paths II

来源:互联网 发布:英文域名注册 编辑:程序博客网 时间:2024/04/28 03:38

Description:
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.

My Solution:

//实际上leetCode的discussion中有很多解法具有一定的迷惑性,它们是倒着来看的,从[0,0]到[m - 1,n - 1]转化为[m - 1,n - 1]到[0,0],原本的右下(走法)变为了左上,因此它们可以从第0行遍历到第m - 1行。而我的解法是还是正着看,因此是从m - 1行开始遍历class Solution {    public int uniquePathsWithObstacles(int[][] obstacleGrid) {        int m = obstacleGrid.length;        int n = obstacleGrid[0].length;        int[] dp = new int[n];        dp[n - 1] = 1;        for(int i = m - 1;i >= 0;i--){            for(int j = n - 1;j >= 0;j--){                if(obstacleGrid[i][j] == 1){                    dp[j] = 0;                }else if(j < n - 1){                    dp[j] += dp[j + 1];                }            }        }        return dp[0];    }}