63. **Unique Paths II

63. **Unique Paths II

https://leetcode.com/problems/unique-paths-ii/description/

题目描述

Follow up for 62. 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]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

Note: m and n will be at most 100.

解题思路

在上一题的基础上, 如果某些空格是不能走的, 存在障碍物, 那么到达 grid 的右下角有多少种走法?

思路: 注意两点:

  • 初始化的的时候, 如果 obstacleGrid = {0, 1, 0, 0}, 那么 dp 的结果就是 {1, 0, 0, 0}, 而不是 {1, 0, 1, 1}, 因为有障碍物, 所有障碍物的位置以及它后面的位置都不能走, 但注意, 是初始化的时候;
  • 仅在 obstacleGrid[i][j] != 1 时, d[i][j] = d[i - 1][j] + d[i][j - 1] 成立.

C++ 实现 1

注意 dp 被设置为 vector<vector<long long>>, 是因为如果设置为 vector<vector<int>>, 那有个测试用例会导致报错:

Line 44: Char 45: runtime error: signed integer overflow: 1053165744 + 1579748616 cannot be represented in type 'int' (solution.cpp)

设置为 long long 可以避免. 但两年前的提交代码中使用的就是 vector<vector<int>> 能通过 100% 的测试用例. 时代变了啊.

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
    	// 一开始就是障碍物, 那么就不用走了.
        if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0]) return 0;
        int m = obstacleGrid.size(), n = obstacleGrid[0].size();
        vector<vector<long long>> dp(m, vector<long long>(n, 0));
        for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i)
            dp[i][0] = 1;
        for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j)
            dp[0][j] = 1;
        for (int i=1; i<m; i++) {
            for (int j=1; j<n; j++) {
                if (!obstacleGrid[i][j])
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
};

C++ 实现 2

具体思路可以参考 62. Unique Paths**
代码来自: 4ms O(n) DP Solution in C++ with Explanations

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        int m = obstacleGrid.size() , n = obstacleGrid[0].size();
        vector<vector<long long>> dp(m+1,vector<long long>(n+1,0));
        dp[0][1] = 1;
        for(int i = 1 ; i <= m ; ++i)
            for(int j = 1 ; j <= n ; ++j)
                if(!obstacleGrid[i-1][j-1])
                    dp[i][j] = dp[i-1][j]+dp[i][j-1];
        return dp[m][n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值