120. Triangle
题目描述
给定一三角形,找出从顶部到底部的最小路径和。每步只能移动到改行下面的向量数字。
例子
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
从顶到底部的最小路径和为11(2+3+5+1=11)
思想
(DP)
dp[i][j]表示到第i行第j列的最小路径和
解法
常规 - DP。复杂度:时间O(n^2),空间O(n^2)。
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = [[0] * (i+1) for i in range(n)] # dp[i][j] --- row-i, col-j
dp[0][0] = triangle[0][0]
for i in range(1, n):
for j in range(i+1):
if j == 0:
dp[i][j] = dp[i-1][j] + triangle[i][j]
elif j == i:
dp[i][j] = dp[i-1][j-1] + triangle[i][j]
else:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]
return min(dp[-1])
(优化 - 减少不必要的边界:行逆序 )
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = [[0] * (i+1) for i in range(n)] # dp[i][j] --- row-i, col-j
dp[-1] = triangle[-1]
for i in range(n-2, -1, -1):
for j in range(i+1):
dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j]
return dp[0][0]
(空间优化1)-trick 在原输入上直接操作,空间O(1)。
class Solution(object):
def minimumTotal(self, triangle):
n = len(triangle)
for i in range(n-2, -1, -1):
for j in range(i+1):
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])
return triangle[0][0]
(空间优化2)
复杂度:时间O(n^2),空间O(n)。
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = triangle[-1] # dp[j] --- col-j
for i in range(n-2, -1, -1):
for j in range(i+1):
dp[j] = min(dp[j], dp[j+1]) + triangle[i][j]
return dp[0]
63. Unique Paths II
题目描述
一个机器人位于m*n棋盘的左上角。机器人只能向下/有移动。现想要机器人到达右下角,棋盘上可能有障碍物(标记为1)。
问有多少种不同的路径?
例子
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1.Right -> Right -> Down -> Down
2.Down -> Down -> Right -> Right
思想
(DP)
dp[i][j]表示到位置(i, j)的不同的路径数。
解法
常规DP。复杂度:时间O(m*n),空间O(m*n)。
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
for j in range(n):
if obstacleGrid[0][j] == 0:
dp[0][j] = 1
else:
break
for i in range(m):
if obstacleGrid[i][0] == 0:
dp[i][0] = 1
else:
break
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]