[动态规划] leetcode 63 Unique Paths II

时间:2019-08-09
本文章向大家介绍[动态规划] leetcode 63 Unique Paths II,主要包括[动态规划] leetcode 63 Unique Paths II使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

problem:https://leetcode.com/problems/unique-paths-ii

       爬台阶类型问题(2D), 如果当前位置有障碍物就不进行状态转换。

class Solution 
{
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) 
    {
        if (obstacleGrid.size() == 0) return 0;
        if (obstacleGrid.size() == 1 && obstacleGrid[0].size() == 1)
        {
            return !obstacleGrid[0][0];
        }
        int n = obstacleGrid.size();
        int m = obstacleGrid[0].size();
        if (obstacleGrid[n - 1][m - 1]) return 0;
        vector<vector<unsigned long long>> dp(n, vector<unsigned long long>(m, 0));
        dp[0][0] = !obstacleGrid[0][0];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (i != 0 || j != 0)
                {
                    unsigned long long x = i >= 1 && obstacleGrid[i - 1][j] == 0 ? dp[i - 1][j] : 0;
                    unsigned long long y = j >= 1 && obstacleGrid[i][j - 1] == 0 ? dp[i][j - 1] : 0;
                    dp[i][j] = x + y;
                }
            }
        }
        return dp[n - 1][m - 1];
    }
};

原文地址:https://www.cnblogs.com/fish1996/p/11328104.html