63. 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).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
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.
1 | [ |
The total number of unique paths is 2
.
Note: m and n will be at most 100.
大意
从一个位置走到另一个位置,中间有障碍,问一共有多少种走法。62题的升级版。
答案
1 | class Solution { |
思路
使用动态规划,声明一个hang lie大小的数组,每个位置表示到这个位置有多少种走法,没有障碍物的时候,可以知道对于一个 hang lie 大小的矩阵,第一行所有数都是1,第一列所有数都是1,因为都是只有一种走法,对于其他位置,状态转移方程是dp[i][j]=dp[i][j-1]+dp[i-1][j]
,也就是说每一个点的位置等于它上面的数加上左边的数的和,通过这样写出状态转移方程,然后从头遍历到尾即可。
加强版
添加了障碍后,有了一个变化,那就是在第一列或者第一行中,只要有一个障碍物,那个障碍物的那个点能到的步数为0,这个点后面的所有地方能到的也为0,所以在赋值的时候需要特殊处理。
然后在遍历的时候也要去掉障碍物。
tips
声明一个n个大小的vector<vector
vector<vector
Author: corn1ng
Link: https://corn1ng.github.io/2017/11/17/算法/leetcode63/
License: 知识共享署名-非商业性使用 4.0 国际许可协议