[leetcode]Unique Paths II

动态规划。再最左和最上加了0的一行一列。但是一开始忘了把mx[1][1]设成1了。

public class Solution {

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {

        // Start typing your Java solution below

        // DO NOT write main() function

        int m = obstacleGrid.length;

        if (m == 0) return 0;

        int n = obstacleGrid[0].length;

        if (n == 0) return 0;

        

        int[][] mx= new int[m+1][n+1];

        for (int i = 0; i <= m; i++) {

            mx[i][0] = 0;

        }      

        for (int j = 0; j <= n; j++) {

            mx[0][j] = 0;

        }

        

        for (int i = 1; i <= m; i++) {

            for (int j = 1; j <= n; j++) {

                if (obstacleGrid[i-1][j-1] == 1) {

                    mx[i][j] = 0;

                }

                else {

                    if (i == 1 && j == 1) mx[i][j] = 1;

                    else mx[i][j] = mx[i][j-1] + mx[i-1][j];

                }                

            }

        }

        

        return mx[m][n];

    }

}

  

你可能感兴趣的:(LeetCode)