63. Unique Paths II/不同路径 II

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?


63. Unique Paths II/不同路径 II_第1张图片

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:

Input:
[
[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

AC代码

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

总结

本质动态规划,题有一个坑,路径数组必须要long,int会爆,但还是返回int,并不会炸

你可能感兴趣的:(63. Unique Paths II/不同路径 II)