Unique Paths II

Posted xpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

63. Unique Paths II

LeetCode: 63. Unique Paths II(Medium)

Unique Paths II

Unique Paths II

63. Unique Paths II

63. Unique Paths II