[LeetCode]63. Unique Paths II

63. Unique Paths II

分析:在原来I的基础之上加上了障碍物,所以只需要碰见障碍物就将该路径置为0,如果是第一行或者第一列存在障碍物,那么在障碍物之后的数就都为0,因为根本不可能到达。

状态转移方程为:

dp[i][j] = 0 (if arr[i][j] == 1)
dp[i][j] = 1 (if arr[i][j] != 1 and (i == 0 or j == 0))
dp[i][j] = dp[i-1][j] + dp[i][j-1] (if arr[i][j] != 1 and i != 0 and j != 0)

动态规划

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        dp = []
        row, col = len(obstacleGrid), len(obstacleGrid[0])
        for i in range(row):
            dp.append([0] * col)
        # 第一行
        for i in range(row):
            if obstacleGrid[i][0] != 1:
                dp[i][0] = 1
            else:
                break
        # 第一列
        for j in range(col):
            if obstacleGrid[0][j] != 1:
                dp[0][j] = 1
            else:
                break 
        for i in range(1, row):
            for j in range(1, col):
                if obstacleGrid[i][j] != 1:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
                else:
                    dp[i][j] = 0
        return dp[row-1][col-1]

还可以将二维数组浓缩成一维数组,如下:

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        if not obstacleGrid or not obstacleGrid[0]:
            return 0
        row, col = len(obstacleGrid), len(obstacleGrid[0])
        dp = [0] * col
        for j in xrange(col):
            if obstacleGrid[0][j]:
                break
            dp[j] = 1
        for i in xrange(1, row):
            for j in xrange(col):
                if obstacleGrid[i][j]:
                    dp[j] = 0
                else:
                    left = dp[j - 1] if j > 0 else 0
                    dp[j] += left
        return dp[col - 1]
posted @ 2017-08-20 02:28  banananana  阅读(136)  评论(0)    收藏  举报