题目:

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. RING0到RING3

    在前一篇文章里面,我们将了CPU保护模式中的几种特权RING0,RING1,RING2,RING3!操作系统通常运行在RING0,应用程序通常运行在RING3. CPU如何从RING0到RING3 先 ...

  2. Eucalyptus常用查询命令

    前言: Elastic Utility Computing Architecture for Linking Your Programs To Useful Systems (Eucalyptus)  ...

  3. python3基础10(操作日志)

    #!/usr/bin/env python# -*- coding:UTF-8 -*- import logging, time, os # 这个是日志保存本地的路径log_path = " ...

  4. pc端的动态效果

    一 图片围绕着某一个确定的圆心运动 几张图片在一个圆开始运动的几种情况 https://github.com/GainLoss/Plug-in-unit 这里面有两种情况

  5. Ubuntu中文乱码问题

    版本 Ubuntu 14.1 系统安装完成后,中文都显示成了乱码 终端或者命令行里输入 sudo apt-get install zhcon 等安装完即可~ 运行的时候记得要加载vgz驱动和utf8支 ...

  6. python_38_try-except异常处理语句及raise的使用

    # i=10 # print(30/(i-10)) # #程序将会出现以下报错信息 # # Traceback (most recent call last): # # File "C:/U ...

  7. ubuntu web server ipython notebook install

    http://blog.csdn.net/yehuohan/article/details/51389966 ipython notebook installhttp://blog.csdn.net/ ...

  8. vue 自定义动态弹框

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. Java 获取Web项目相对webapp地址

    例如, import java.io.File; import java.io.FileInputStream; import javax.servlet.http.HttpServletReques ...

  10. 【函数应用】PHP中关于URL的函数处理

    一,函数介绍 1.解析HTTP头信息:get_header() array get_headers ( string 目标URL [, int $format = 0 [如果将可选的 format 参 ...