博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
63. Unique Paths II
阅读量:4649 次
发布时间:2019-06-09

本文共 2302 字,大约阅读时间需要 7 分钟。

题目:

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.

[  [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.

链接:

4/26/2017

1ms, 19%

跟unique paths差不多,区别是,如果是障碍那么dp为0,并且初始化边界的时候也要注意这个条件。

注意的问题:

1. 判断非法输入

2. 在初始化第一行和第一列的时候就要想到有obstacle,所以要判断是否当前为障碍,以及如果之前一个dp是0,现在的也应该是0

3. 注意typo,不要随便copy & paste,比如第8行开始是obstacleGrid,后面是dp

1 public class Solution { 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3         if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 4  5         int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length]; 6  7         for (int i = 0; i < obstacleGrid.length; i++) { 8             if (obstacleGrid[i][0] == 1 || i > 0 && dp[i - 1][0] == 0) { 9                 dp[i][0] = 0;10             } else {11                 dp[i][0] = 1;12             }13         }14         for (int i = 0; i < obstacleGrid[0].length; i++) {15             if (obstacleGrid[0][i] == 1 || i > 0 && dp[0][i - 1] == 0) {16                 dp[0][i] = 0;17             } else {18                 dp[0][i] = 1;19             }20         }21         for (int i = 1; i < obstacleGrid.length; i++) {22             for (int j = 1; j < obstacleGrid[0].length; j++) {23                 if (obstacleGrid[i][j] == 1) {24                     dp[i][j] = 0;25                 } else {26                     dp[i][j] = dp[i][j - 1] + dp[i - 1][j];27                 }28             }29         }30         return dp[obstacleGrid.length - 1][obstacleGrid[0].length - 1];31 32     }33 }

别人的算法

一维DP

1 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 2     int width = obstacleGrid[0].length; 3     int[] dp = new int[width]; 4     dp[0] = 1; 5     for (int[] row : obstacleGrid) { 6         for (int j = 0; j < width; j++) { 7             if (row[j] == 1) 8                 dp[j] = 0; 9             else if (j > 0)10                 dp[j] += dp[j - 1];11         }12     }13     return dp[width - 1];14 }

更多讨论:

转载于:https://www.cnblogs.com/panini/p/6772835.html

你可能感兴趣的文章
openwrt gstreamer实例学习笔记(四. gstreamer Bins)
查看>>
信息安全系统设计基础第八周学习总结
查看>>
Maven - 继承和聚合
查看>>
leetcode_Basic Calculator II
查看>>
B+树
查看>>
Python中functools模块函数解析
查看>>
《Java大学教程》—第17章 Java聚焦类框架
查看>>
PAT——1074. 宇宙无敌加法器(20)
查看>>
迟到的tkinter---学校选课刷屏器
查看>>
[转载] 深入理解Linux修改hostname
查看>>
通过生日查询各年龄段数量通过饼状图显示
查看>>
WPF仿制IOS UI(未完待续)
查看>>
NOIP2018 No regrets youth
查看>>
BayaiM__SQLLDR_linux_shell高级版
查看>>
蓝桥杯历届试题 地宫取宝 dp or 记忆化搜索
查看>>
如何配置Smarty模板
查看>>
hdu1222
查看>>
从函数返回数组
查看>>
Rsync学习之旅上
查看>>
eclipse简单使用
查看>>