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 };
  • 相关阅读:
    having——至少被订购过两回的订单
    产品——仓库表查询
    SQL 聚集函数使用
    select count(*)和select count(1)的区别 (转)
    SpringAOP 通知(advice)
    Spring AOP 实现原理与 CGLIB 应用
    cglib 动态代理基础篇
    模仿Struts2的Interceptor拦截器实现
    利用JDK动态代理机制实现简单拦截器
    java多线程总结二:后台线程(守护线程)
  • 原文地址:https://www.cnblogs.com/wxquare/p/4986923.html
Copyright © 2011-2022 走看看