题目:

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.

代码:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> >& obstacleGrid)
{
const int m = obstacleGrid.size();
const int n = obstacleGrid[].size();
vector<vector<int> > cache(m+,vector<int>(n+,));
return Solution::dfs(m, n, cache, obstacleGrid);
}
static int dfs( int i, int j, vector<vector<int> >& cache, vector<vector<int> >& obstacleGrid )
{
if ( i< || j< || obstacleGrid[i-][j-]== ) return ;
if ( i== && j== ) return ;
return Solution::getDFS(i-, j, obstacleGrid, cache) + Solution::getDFS(i, j-, obstacleGrid, cache);
}
static int getDFS(int i, int j, vector<vector<int> >& obstacleGrid, vector<vector<int> >& cache)
{
if ( cache[i][j]> ){
return cache[i][j];
}
else{
return cache[i][j] = Solution::dfs(i, j, cache, obstacleGrid);
}
}
};

tips:

上述的代码采用了深搜+缓存(“备忘录”)法。照比Unique Paths多了一个判断条件,如果obstacleGrid上该位置为1则直接返回0。

有个细节上的技巧:

obstacleGrid是题目给出的定义,下标[m-1][n-1]

cache是自定义的缓存数组,下标[m][n]

同样的位置,cache的坐标比obstacleGrid大1;因此,只要深搜过程中保证了cache的坐标在合理范围内,无论是横坐标-1还是纵坐标-1,映射到cache的坐标中总不会越界。

上述代码的效率并不高,但是比较容易处理各种case。再尝试动态规划的解法。

==========================================

在Unique Paths的基础上,用动规又把Unqiue Paths II写了一遍。

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> >& obstacleGrid)
{
const int m = obstacleGrid.size();
const int n = obstacleGrid[].size();
vector<int> dp(n, );
if ( obstacleGrid[][]== ) return ;
dp[] = ;
for ( size_t i = ; i < m; ++i )
{
dp[] = obstacleGrid[i][]== ? : dp[];
for ( size_t j =; j < n; ++j )
{
dp[j] = obstacleGrid[i][j]== ? : dp[j-] + dp[j];
}
}
return dp[n-];
}
};

tips:

沿用了滚动数组的技巧,额外空间缩减为O(n),代码的效率也提升了。

==========================================

第二次过这道题,用dp过的。

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty()) return ;
const int m = obstacleGrid.size();
const int n = obstacleGrid[].size();
int dp[m][n];
fill_n(&dp[][], m*n, );
for ( int i=; i<n; ++i )
{
if ( obstacleGrid[][i]== )
{
dp[][i]=;
}
else
{
break;
}
}
for ( int i=; i<m; ++i )
{
if ( obstacleGrid[i][]== )
{
dp[i][]=;
}
else
{
break;
}
}
for ( int i=; i<m; ++i )
{
for ( int j=; j<n; ++j )
{
if ( obstacleGrid[i][j]== )
{
dp[i][j] = dp[i-][j] + dp[i][j-];
}
}
}
return dp[m-][n-];
}
};

【Unique Paths II】cpp的更多相关文章

  1. leetcode 【 Unique Paths II 】 python 实现

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  2. 【Path Sum II】cpp

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  3. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  4. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  5. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  6. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  7. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  8. 【Jump Game II 】cpp

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

  9. 【Single Num II】cpp

    题目: Given an array of integers, every element appears three times except for one. Find that single o ...

随机推荐

  1. 又一例网卡mtu值引发的问题

    通过php上传文件到云存储,很小的文件都无法上传,在别的服务器上测试可以,本机环境是ESXI虚机安装的centos 7版本 解决思路过程 1.让开发写一个单独测试上传的文件,不调php nginx配置 ...

  2. Nginx+Keepalived双主轮询负载均衡

    双主模式使用两个VIP,前段有2台服务器,互为主从,两台服务器同时工作,不存在资源浪费情况.同时在前端的DNS服务器对网站做多条A记录,实现了Nginx的负载均衡,当一台服务器故障时候,资源会转移到另 ...

  3. java 串口通信实现流程

    1.下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java 2.下载下来的包解压后按照说明放到JAVA_HOME即JAVA的安装路径下面去 ...

  4. 日常-acm-排列

    用1-9组成三个数abc,def,ghi,每个数字恰好出现一次,要求abc:def:ghi=1:2:3.按照“abc def ghi”输出所有解,每行一个解. #include <iostrea ...

  5. IOS PickerView使用

    - (void)viewDidLoad { [super viewDidLoad]; // 1.创建pickerview // pickerview有默认的frame UIPickerView *pi ...

  6. 前台使用load一个集合后台接受的方法

    前台: var imageCaseList = []; }; imageCaseList.push(data); $('#showData').load(url, { querys: imageCas ...

  7. Aizu 2170 Marked Ancestor(并查集变形)

    寻找根节点很容易让人联想到DisjointSet,但是DisjointSet只有合并操作, 所以询问离线倒着考虑,标记会一个一个消除,这时候就变成合并了. 因为询问和查询的时间以及标记生效的时间有关, ...

  8. 【51nod1743】雪之国度(最小生成树+倍增)

    点此看题面 大致题意: 给你一张无向连通图,其中每条边的边权为这条边连接的两点的权值之差.每次询问两点之间是否存在两条不重复的路径,若存在则输出这两条路径上最大值的最小值. 大致思路 这题显然就是要让 ...

  9. node第一天

    一.主要执行的文件命名一般为main.js var aModule =require('./a.js');//相对路径 var aModule =require('a.js');//专门从node_m ...

  10. vitrual box安装centos时一直黑屏的解决办法

    趁着清明节没事,昨天看了mysql性能优化后,想装个linux系统学习下,linux一直是我的短板...之前是在vmware上安装ubuntu,买了新电脑后,听过virtual box相比vmware ...