首页 > 代码库 > Unique Paths II

Unique Paths II

 方法一:动态规划

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

方法二:备忘录法

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size(), n = obstacleGrid[0].size();
        fm = vector<vector<int>>(m, vector<int>(n, 0));
        
        fm[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1;
        return dfs(obstacleGrid, m-1, n-1);
    }
    
private:
    vector<vector<int>> fm;
    
    int dfs(vector<vector<int>>& obstacleGrid, int m, int n)
    {
        if(m < 0 || n < 0)
            return 0;
        if(obstacleGrid[m][n])
            return 0;
        if(m == 0 && n == 0)
            return fm[0][0];
            
        if(fm[m][n] > 0)
            return fm[m][n];
        else
            return fm[m][n] = dfs(obstacleGrid, m-1, n) + dfs(obstacleGrid, m, n-1);
    }
};

 

Unique Paths II