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

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

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.

与, 题目解法类似,都是DP问题。建立一个新的矩阵,矩阵每个元素记录的是从upper left到该点的路径数。与Unique Path不同的是:写递归式的时候,能不能代入下一层递归需要检验obstacleGrid里该点是不是一个obstacle,如果是,该层返回0且不继续递归

一维DP解法:

1 public class Solution { 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3         int[][] grid = obstacleGrid; 4         int xLen = grid.length; 5         if (xLen==0) return 0; 6         int yLen = grid[0].length; 7         if (yLen==0) return 0; 8          9         int[] path = new int[yLen];10         if (grid[0][0]==1)11             return 0;12         else path[0] = 1;13         for (int i=1;i

 

 

Iteration方法:21-26行可删,因为如果那里是obstacle,那里在res矩阵里也是0,加它也无妨

1 public class Solution { 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3         int m = obstacleGrid.length; 4         int n = obstacleGrid[0].length; 5         int[][] res = new int[m][n]; 6         for (int k=0; k

 

转载地址:http://dcqpl.baihongyu.com/

你可能感兴趣的文章
汉语国际传播思索
查看>>
apache .htaccess重写去除index.php
查看>>
linux Cp .md
查看>>
迅雷软件或将成最大×××散播工具
查看>>
Windows中UltraEdit ctags的配置(2010.4.28更新)
查看>>
TODO:排列组合问题:n个数中取m个
查看>>
27.chown更换所有者
查看>>
grep、egrep以及正则表达式的使用
查看>>
rsync加inotify实现无间隔文件同步
查看>>
系统最小化安装后,使用命令时提示“command not found”
查看>>
ffmpeg2.x开始支持opencl,编译测试
查看>>
python 抽象类分析
查看>>
DNS基本使用--主从服务器的搭建、主从同步、子域授权的实现
查看>>
centos 7
查看>>
java获取路径的方法
查看>>
IK中文分词_IK分词器配置文件讲解以及自定义词库
查看>>
One or more constraints have not been satisfied.
查看>>
redis慢查询日志,php安装redis扩展,redis存储session,redis主从配置
查看>>
RBAC扩展
查看>>
Java函数式编程和lambda表达式
查看>>