[leetcode] 63. Unique Paths II 解题报告

题目链接:https://leetcode.com/problems/unique-paths-ii/

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.


思路: 和上一个一样都是动态规划的题目,只是稍微有点不同,就是多了不可以走的格子,所以不可以走的地方就直接可以设为到这里的路径为0。时间复杂度为O(M*N),空间复杂度为O(M*N)。具体代码如下:

class Solution {
public:
    int uniquePathsWithObstacles(vector>& obstacleGrid) {
        if(obstacleGrid.size()==0) return 0;
        int row = obstacleGrid.size(), col = obstacleGrid[0].size();
        vector> dp(row+1, vector(col+1, 0));
        dp[0][1] = 1;
        for(int i = 1; i <= row; i++)
        {
            for(int j = 1; j <= col; j++)
            {
                if(obstacleGrid[i-1][j-1]==1) dp[i][j] = 0;
                else dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[row][col];
    }
};


你可能感兴趣的:(动态规划,leetcode)