zoukankan      html  css  js  c++  java
  • leetCode+Unique Paths II

    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,
    �ere is one obstacle in the middle of a 3 × 3 grid as illustrated below.
    [
    [0,0,0],
    [0,1,0],
    [0,0,0]
    ]
    �e total number of unique paths is 2.
    Note: m and n will be at most 100.

    方法一:DFS

    class Solution {
    public:
        int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
            if(obstacleGrid.empty()) return 0;
    
            int m = obstacleGrid.size();
            int n = obstacleGrid[0].size();
            if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;
    
            int **buffer = new int* [m+1];
            for(int i=0;i<=m;i++){
                buffer[i] = new int [n+1];
                fill(buffer[i],buffer[i]+n+1,0);
            }
            int temp = dfs(obstacleGrid,m,n,buffer);
            for(int i=0;i<=m;i++)
                delete [] buffer[i];
            delete [] buffer;
            return temp;
        }
    
        int dfs(vector<vector<int>> &obstacleGrid,int x,int y,int** buf){
            if(x < 1 || y < 1) return 0;
            if(obstacleGrid[x-1][y-1]) return 0;
            if(buf[x][y]>0) return buf[x][y];
            if(x == 1 && y==1 ) return 1;
    
            buf[x-1][y] = dfs(obstacleGrid, x-1, y, buf); 
            buf[x][y-1] = dfs(obstacleGrid, x, y-1, buf);
            return buf[x][y] = buf[x-1][y]+buf[x][y-1];
        }
    };

    方法二:DP

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
     4         if(obstacleGrid.empty()) return 0;
     5 
     6         int m = obstacleGrid.size();
     7         int n = obstacleGrid[0].size();
     8         if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;
     9         int *buf = new int [n];
    10         fill(buf,buf+n,0);
    11 
    12         buf[0] = 1;
    13         for(int i=0;i < m;i++){
    14             for(int j=0;j<n;j++){
    15                 buf[j] = obstacleGrid[i][j] ? 0 : (j == 0 ? 0 : buf[j-1]) + buf[j]; 
    16             }
    17         }
    18         return buf[n-1];
    19     }
    20 };
  • 相关阅读:
    快排算法的一点思考
    imglab .xml 标签格式转coco .json格式
    Ubuntu18.04 编译 sparse-ncnet
    Detectron2 keypoint_rcnn 网络c++版本部署
    技术部斗争
    我的程序人生
    关于ddd落地体验
    DevOps关于制定适合自身生产环境的redis集群
    从前端到后端的跨域攻击与防御
    DKIM对发送邮件的好处及使用方法
  • 原文地址:https://www.cnblogs.com/wxquare/p/4986923.html
Copyright © 2011-2022 走看看