代码随想录算法训练营第四十三天| 第九章 动态规划:1049.最后一块石头的重量II,494.目标和,474.一和零(python)

目录

1049.最后一块石头的重量II

494.目标和

474.一和零


1049.最后一块石头的重量II

视频讲解链接  文字讲解链接

class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:  
        target = sum(stones) // 2 #尽可能分成两等分,这样相撞之后差最小 
        dp = [0] * (target + 1)
        for i in range(len(stones)):
            for j in range(target, stones[i]-1, -1):
                dp[j] = max(dp[j], dp[j-stones[i]] + stones[i])
        return sum(stones) - 2 * dp[target]

494.目标和

视频讲解链接  文字讲解链接

class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        total = sum(nums)
        if abs(target) > total or (total+ target)% 2:
            return 0
        bagsize = (total + target) // 2
        dp = [0] * (bagsize+1)
        dp[0] = 1

        for i in range(len(nums)):
            for j in range(bagsize, nums[i]-1, -1):
                dp[j] += dp[j-nums[i]]
        return dp[bagsize]

474.一和零

视频讲解链接  文字讲解链接

class Solution:
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        dp = [[0] * (n+1) for _ in range(m+1)]

        for str in strs:
            x = str.count('0')
            y = str.count('1')
            for i in range(m, x-1, -1):
                for j in range(n, y-1, -1):
                    dp[i][j] = max(dp[i][j], dp[i-x][j-y]+1) #最多有i个‘0’,j个‘1’的背包中最多装了多少物品
        
        return dp[m][n]

你可能感兴趣的:(动态规划,算法,leetcode,python)