115. 不同的路径 II

115. 不同的路径 II

中文English

"不同的路径" 的跟进问题:

现在考虑网格中有障碍物,那样将会有多少条不同的路径?

网格中的障碍和空位置分别用 1 和 0 来表示。

样例

Example 1:
	Input: [[0]]
	Output: 1


Example 2:
	Input:  [[0,0,0],[0,1,0],[0,0,0]]
	Output: 2
	
	Explanation:
	Only 2 different path.
	

注意事项

m 和 n 均不超过100

输入测试数据 (每行一个参数)如何理解测试数据?
class Solution:
    """
    @param obstacleGrid: A list of lists of integers
    @return: An integer
    """
    """
    大致思路:
    1.确定状态
    最后一步:dp[i - 1][j - 1]
    子问题:dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

    2.转移方程

    3.初始条件和边界情况
    l_x = len(obstacleGrid)
    l_y = len(obstacleGrid[0])
    dp = [[0]*l_y for _ in len(obs)*l_x]

    如果是障碍物
    dp[i][j] = 0

    对于边界情况
    1.比如[0][0],dp[0][0] = 1
    2.对于i = 0,则也为dp[0][j] = 1,如果当前是障碍物,则后面均为0,直接break即可
    3.对于j = 0,同上
    
    对于不是边界情况:
    如果当前是障碍物:
    dp[i][j] = 0 
    continue
    
    继续处理下一个
    dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

    4.计算顺序
    内外循环
    """
    def uniquePathsWithObstacles(self, obstacleGrid):
        # write your code here
        if not obstacleGrid:return 0

        #初始化
        l_x = len(obstacleGrid)
        l_y = len(obstacleGrid[0])
        dp = [[0]*l_y for _ in range(l_x)]
        dp[0][0] = 1

        for index in range(l_y):
            if obstacleGrid[0][index] == 1:
                break
            dp[0][index] = 1
        
        for index in range(l_x):
            if obstacleGrid[index][0] == 1:
                break
            dp[index][0] = 1
                    
        #计算顺序
        for i in range(1,l_x):
            for j in range(1,l_y):
                if (obstacleGrid[i][j] == 1):
                    dp[i][j] = 0
                    continue
                
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

        return dp[l_x - 1][l_y - 1]
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13028775.html