Unique Paths 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?
An obstacle and empty space is marked as
1
and0
respectively in the grid.Note: m and n will be at most 100.
Example 1
1 | Input: |
解题思路
动态规划。若当前位置是障碍,则到达该位置的路径数为零;否则,路径数=左单元路径数+上单元路径数。
复杂度分析
- 时间复杂度:$O(mn)$。
- 空间复杂度:$O(1)$,可直接利用
obstacleGrid
。
代码
1 | class Solution { |