1.LeetCode974 模拟行走机器人
控制机器人行走的基本思想是:先更新方向变化,再以 步长1 更新坐标。
需要注意的是,原题解中提到:必须注意使用 集合 Set 作为对障碍物使用的数据结构,以便我们可以有效地检查下一步是否受阻。如果不这样做,我们检查障碍点的速度可能会慢大约 10000 倍。
class Solution:
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
ans=0
d={'+x':0,'-x':0,'+y':0,'-y':0}
f={'+x':1,'-x':1,'+y':0,'-y':0}
obstacleSet = set(map(tuple, obstacles)) #关键步
direction='+y'
direction_change={'+y-1':'+x','+y-2':'-x','-y-2':'+x','-y-1':'-x','+x-2':'+y','+x-1':'-y','-x-2':'-y','-x-1':'+y'}
x=0
y=0
for i in commands:
if i>0:
for k in range(i):
d[direction]+=1
coordinate = (d['+x'] - d['-x'], d['+y'] - d['-y'])
if coordinate in obstacleSet:
d[direction]-=1
break
else:
direction=direction_change[direction+str(i)]
ans=max(([d['+x']-d['-x'],d['+y']-d['-y']][0]**2+[d['+x']-d['-x'],d['+y']-d['-y']][1]**2),ans)
return(ans)
2.LeetCode62 不同路径
排列组合思想,机器人一共要行走m+n-2步,其中有m-1步要向下,计算下行组合的数量即为不同路径的数量。
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# C^(m-1)_(m+n-2)
res = 1
for i in range(m, m+n-1):
res *= i
res /= i-m+1
return int(res)
#代码源于LeetCode提交记录提交用时最少的范例。