[算法] 刷题-动态规划

拟墨画扇 提交于 2020-04-08 12:16:07

索引

  • 最大正方形
  • 最短三角形路径
  • 最大子序和

题解

  • 最大正方形
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!