博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] unique paths ii 独特路径
阅读量:4640 次
发布时间:2019-06-09

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

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 as1and0respectively 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 is2.

Note: m and n will be at most 100.

 题意:增加障碍,不能到达障碍,不能越过障碍。

思路:思路和是一样的,只是要判断当前值是否为1,若是,则其对应的dp数组中赋值为0,不是时,状态方程是:dp[i][j]=dp[i-1][j]+dp[i][j-1]。代码如下:

1 class Solution { 2 public: 3     int uniquePathsWithObstacles(vector
> &obstacleGrid) 4 { 5 int m=obstacleGrid.size(),n=obstacleGrid[0].size(); 6 vector
> dp(m,vector
(n,0)); 7 if(m==0||n==0) return 1; 8 if(obstacleGrid[0][0]==1) return 0; 9 dp[0][0]=1; 10 //初始行11 for(int i=1;i

 

 当用一维数组去简化时,要注意些问题,仅一行,或者仅一列时,还要依次的确定数组dp[]中对应的值,不是像上一题那样简单赋值为1就行,所以,遍历时,行和列的起始点都是从0开始;另外也得注意的是,数组dp中的当前的前一个是否存在,即, j >0。代码如下:

1 class Solution { 2 public: 3     int uniquePathsWithObstacles(vector
> &obstacleGrid) 4 { 5 int row=obstacleGrid.size(),col=obstacleGrid[0].size(); 6 if(obstacleGrid[0][0]==1) return 0; 7 vector
dp(col,0); 8 dp[0]=1; 9 10 for(int i=0;i
0)17 dp[j]+=dp[j-1];18 }19 }20 return dp[col-1]; 21 }22 };

 

转载于:https://www.cnblogs.com/love-yh/p/7121787.html

你可能感兴趣的文章
far和near
查看>>
Python爬虫实战四之抓取淘宝MM照片
查看>>
2015 Multi-University Training Contest 1
查看>>
C#判断一个字符串是否是数字或者含有某个数字
查看>>
SVN使用指南
查看>>
【转载】掌 握 3 C ‧ 迎 接 亮 丽 职 涯
查看>>
爬取网站附件
查看>>
java基础图形界面和IO系统
查看>>
javascript学习笔记
查看>>
hdu 3996
查看>>
python第三十九课——面向对象(二)之初始化属性
查看>>
python学习笔记之函数装饰器
查看>>
FEM计算2D瞬态热传导方程
查看>>
四年时光,匆匆而过
查看>>
【php】【psr】psr1 基础编码规范
查看>>
WAF SSI
查看>>
LDAP & it's implementation
查看>>
Apache HttpComponents中的cookie匹配策略
查看>>
冰封的海盗攻略
查看>>
Netty4.x中文教程系列(四) 对象传输
查看>>