[Leetcode] 63. 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.

思路

当obstacleGrid[i][j] == 1时,将dp[i][j]直接设置为0;否则递推关系和Leetcode 62完全相同。其动态规划解法的时间复杂度为O(m*n),空间复杂度还可以优化到O(n)。如果再要继续较真,空间复杂度还可以进一步优化到O(min(m, n))。其中m和n分别是obstacleGrid的列个数和行个数。

代码

class Solution {
public:
    int uniquePathsWithObstacles(vector>& obstacleGrid) {
        int rows = obstacleGrid.size();
        if (rows == 0) {
            return 0;
        } 
        int cols = obstacleGrid[0].size();
        if (cols == 0) {
            return 0;
        }
        vector dp(cols + 1, 0);
        dp[1] = 1;
        for (int y = 1; y <= rows; ++y) {
            for (int x = 1; x <= cols; ++x) {
                if (obstacleGrid[y - 1][x - 1] == 1) {
                    dp[x] = 0;
                }
                else {
                    dp[x] = dp[x - 1] + dp[x];
                }
            }
        }
        return dp[cols];
    }
};


你可能感兴趣的:(IT公司面试习题)