LintCode Q115 Unique in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年12月10日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution:
"""
@param obstacleGrid: An list of lists of integers
@return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
# dynamic programming
# time complexity O(n^2)
if obstacleGrid[0][0] == 1:
return 0
else:
obstacleGrid[0][0] = 1
m = len(obstacleGrid)
n = len(obstacleGrid[0])
for col in xrange(1, n):
if obstacleGrid[0][col] == 0:
obstacleGrid[0][col] = 1
else: # obstacleGrid[0][col] == 1
while (col < n):
obstacleGrid[0][col] = 0
col += 1
break
for row in xrange(1, m):
if obstacleGrid[row][0] == 0:
obstacleGrid[row][0] = 1
else: # obstacleGrid[row][0] == 1
while (row < m):
obstacleGrid[row][0] = 0
row += 1
break
for row in xrange(1, m):
for col in xrange(1, n):
if obstacleGrid[row][col] == 1:
obstacleGrid[row][col] = 0
else:
obstacleGrid[row][col] = obstacleGrid[row - 1][col] + obstacleGrid[row][col - 1]
return obstacleGrid[-1][-1]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。