LeetCode 1824. [Python] Minimum Sideway Jumps
原题链接
中等
作者:
徐辰潇
,
2021-04-17 23:20:20
,
所有人可见
,
阅读 428
class Solution:
def minSideJumps(self, obstacles: List[int]) -> int:
#TC: O(n)
#SC: O(n) easy to optimized to O(1)
n = len(obstacles)
dp = [[0]*3 for i in range(n)]
dp[0][0] = 1
dp[0][1] = 0
dp[0][2] = 1
for i in range(1,n):
if obstacles[i] == 0:
dp[i][0] = min(min(dp[i-1][1], dp[i-1][2])+1, dp[i-1][0])
dp[i][1] = min(min(dp[i-1][0], dp[i-1][2])+1, dp[i-1][1])
dp[i][2] = min(min(dp[i-1][0], dp[i-1][1])+1, dp[i-1][2])
elif obstacles[i] == 1:
dp[i][0] = sys.maxsize
dp[i][1] = min(dp[i-1][2]+1, dp[i-1][1])
dp[i][2] = min(dp[i-1][1]+1, dp[i-1][2])
elif obstacles[i] == 2:
dp[i][1] = sys.maxsize
dp[i][0] = min(dp[i-1][2]+1, dp[i-1][0])
dp[i][2] = min(dp[i-1][0]+1, dp[i-1][2])
elif obstacles[i] == 3:
dp[i][2] = sys.maxsize
dp[i][0] = min(dp[i-1][1]+1, dp[i-1][0])
dp[i][1] = min(dp[i-1][0]+1, dp[i-1][1])
return min(dp[-1])