索引
- 最大正方形
- 最短三角形路径
- 最大子序和
题解
- 最大正方形
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
nums = matrix
if len(nums) ==0 or len(nums[0]) ==0:
return 0
height = len(nums)
width = len(nums[0])
masks = [[0]*(width+1) for i in range(height+1)]
max_len = 0
for j in range(0,height):
for i in range(0,width):
val = int(nums[j][i])
if val == 1:
masks[j+1][i+1] = min(
masks[j][i],
masks[j+1][i],
masks[j][i+1]
) +1
max_len = max(max_len,masks[j+1][i+1])
return max_len*max_len
- 最短三角形路径
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
nums = triangle
if len(nums) ==0 or len(nums[0]) == 0:
return 0
if len(nums) ==1:
return nums[0][0]
height = len(nums)
vals = [0]*height
for idx, floor in enumerate(triangle):
size = len(floor)
for i in range(size-1,-1,-1):
if i == 0:
vals[0] = floor[0] + vals[0]
elif i == size-1:
vals[i] = floor[i] + vals[i-1]
else:
vals[i] = min(vals[i],vals[i-1]) + triangle[idx][i]
m = min(vals)
return m
- 最大子序和
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = list()
dp.append(nums[0])
for i, v in enumerate(nums):
if i == 0:
continue
dp.append(max(dp[i - 1] + nums[i], nums[i]))
m = max(dp)
return m
来源:oschina
链接:https://my.oschina.net/u/4215839/blog/3224560