题目来源:
https://leetcode.com/problems/unique-paths-ii/
题意分析:
这题的规则和上一题一样。给一个m×n的矩阵0,1矩阵。0代表可以经过,1代表不可以通过。返回从(0,0)到(m,n)一共有多少种走法。
题目思路:
这题如果还是用组合的方法做将会非常复杂,所以组合的方法不再考虑。不难发现,从(0,0)到(i,j)的所有可能等于(0,0)到(i - 1,j)和(0,0)到(i,j-1)的和。那么建立一个m×n的表a,a[i][j]代表(0,0)到(i,j)的走法。把表填满,就可以得到结果。时间复杂度是O(m×n)
代码(python):
1 class Solution(object): 2 def uniquePathsWithObstacles(self, obstacleGrid): 3 """ 4 :type obstacleGrid: List[List[int]] 5 :rtype: int 6 """ 7 m,n = len(obstacleGrid),len(obstacleGrid[0]) 8 ans = [[0 for i in range(n)] for j in range(m)] 9 ans[0][0] = 1 10 for i in range(m): 11 for j in range(n): 12 if obstacleGrid[i][j] == 1: 13 ans[i][j] = 0 14 elif i != 0 and j == 0: 15 ans[i][j] = ans[i - 1][j] 16 elif i == 0 and j != 0: 17 ans[i][j] = ans[i][j - 1] 18 elif i != 0 and j != 0: 19 ans[i][j] = ans[i -1][j] + ans[i][j - 1] 20 return ans[m - 1][n - 1]
转载请注明出处:http://www.cnblogs.com/chruny/p/5008277.html