【Leetcode】Unique Paths II
2016-05-25 20:07
507 查看
题目链接:https://leetcode.com/problems/unique-paths-ii/
题目:
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
in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is
Note: m and n will be at most 100.
思路:
动态规划。easy
算法:
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int c[][] = new int[obstacleGrid.length][obstacleGrid[0].length];
c[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0;
for (int i = 1; i < obstacleGrid.length; i++) {
c[i][0] = (c[i-1][0]!=0&&obstacleGrid[i][0] == 0) ? 1 : 0;
}
for (int j = 1; j < obstacleGrid[0].length; j++) {
c[0][j] = (c[0][j-1]!=0&&obstacleGrid[0][j] == 0) ? 1 : 0;
}
for (int i = 1; i < obstacleGrid.length; i++) {
for (int j = 1; j < obstacleGrid[0].length; j++) {
if (obstacleGrid[i][j] != 1){
c[i][j] = c[i - 1][j] + c[i][j - 1];
}
else
c[i][j] = 0;
}
}
return c[obstacleGrid.length - 1][obstacleGrid[0].length - 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.
思路:
动态规划。easy
算法:
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int c[][] = new int[obstacleGrid.length][obstacleGrid[0].length];
c[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0;
for (int i = 1; i < obstacleGrid.length; i++) {
c[i][0] = (c[i-1][0]!=0&&obstacleGrid[i][0] == 0) ? 1 : 0;
}
for (int j = 1; j < obstacleGrid[0].length; j++) {
c[0][j] = (c[0][j-1]!=0&&obstacleGrid[0][j] == 0) ? 1 : 0;
}
for (int i = 1; i < obstacleGrid.length; i++) {
for (int j = 1; j < obstacleGrid[0].length; j++) {
if (obstacleGrid[i][j] != 1){
c[i][j] = c[i - 1][j] + c[i][j - 1];
}
else
c[i][j] = 0;
}
}
return c[obstacleGrid.length - 1][obstacleGrid[0].length - 1];
}
相关文章推荐
- Codeforces Round #FF (Div. 1) A. DZY Loves Sequences 动态规划
- 【MySQL】Error 1264: out of range value for column
- leetcode之longest-consecutive-sequence
- UI控件大全
- myBatis抛出异常Result Maps collection already contains value ...
- [Codeforces297C]Splitting the Uniqueness(构造)
- iOS开发之高级视图—— UITableView(六)表视图刷新
- arduino 资料
- iOS _ UILabel 调整行间距
- SDUT-2169-Sequence(DP)
- find,vim的编程设置,SUID,SGID,SBIT,软.硬链接,重定向
- UILable 设置多种字体颜色
- iOS开发UI篇—核心动画(转场动画和组动画)
- 对AbstractQueuedSychronizer的粗略理解
- Java中String、StringBuffer和StringBuilder的区别和堆栈内存分配
- Helper2416开发板移植minigui3.0.12之二:移植到开发板
- Vue.js-----轻量高效的MVVM框架(九、组件利用Props传递数据)
- IOS音频1:之采用四种方式播放音频文件(一)AudioToolbox AVFoundation OpenAL AUDIO QUEUE
- Arduino入门(二)
- iOS开发UI篇—iPad开发中得modal介绍