[LeetCode]Unique Paths II
2016-10-31 19:43
337 查看
Question
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
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is 2.
Note: m and n will be at most 100.
本题难度Medium。
一维数组
【复杂度】
时间 O(N^2) 空间 O(N)
【思路】
与Unique Paths的一维数组法一样,只不过多了一个障碍,因此对于
但是要注意的情况是
第二行第一列的值为1,那么不仅它的本行
【代码】
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
1and
0respectively 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.
本题难度Medium。
一维数组
【复杂度】
时间 O(N^2) 空间 O(N)
【思路】
与Unique Paths的一维数组法一样,只不过多了一个障碍,因此对于
j!=0的
dp[j]赋值:
dp[j]=(obstacleGrid[i][j]==1)?0:dp[j]+dp[j-1];
但是要注意的情况是
dp[0]的赋值,比如:
[ [0,0,0], [1,0,0], [0,0,0] ]
第二行第一列的值为1,那么不仅它的本行
dp[0]=0,而且对于第三行第一列
dp[0]=0。所以在此,对于
dp[0]值的赋值为:
dp[0]=(dp[0]==0)?0:(obstacleGrid[i][0]==1?0:1);
【代码】
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { //require int m=obstacleGrid.length; if(m<1) return 1; int n=obstacleGrid[0].length; if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1) return 0; int[] dp=new int ; dp[0]=1; for(int i=0;i<m;i++){ dp[0]=(dp[0]==0)?0:(obstacleGrid[i][0]==1?0:1); for(int j=1;j<n;j++) dp[j]=(obstacleGrid[i][j]==1)?0:dp[j]+dp[j-1]; } return dp[n-1]; } }
相关文章推荐
- leetcode 063 —— Unique Paths II
- 【题解】【矩阵】【回溯】【Leetcode】Unique Paths II
- [leetcode]Unique Paths II
- leetcode — unique-paths-ii
- Unique Paths II - LeetCode
- [LeetCode] Unique Paths II 起点与终点确定的路径数II
- [LeetCode] Unique Paths II
- LeetCode | Unique Paths I,II
- Unique Paths II leetcode java
- leetcode - Unique Paths II
- leetcode - Unique Paths II
- [leetcode]Unique Paths II
- [leetcode]Unique Paths II @ Python
- Unique Paths II-leetcode
- leetcode:Unique Paths II
- [LeetCode] Unique Paths II 解题报告
- leetcode_c++:Unique Paths II(063)
- [LeetCode] Unique Paths II
- LeetCode 95. Unique Paths II
- [LeetCode] Unique Paths II