代码随想录训练营第III期--043--python

# 代码随想录训练营第III期--043--python

#  1049. 最后一块石头的重量 II 
def lastStone(stones):
    ss = sum(stones)
    target = ss // 2 
    dp = [0] * 15001 
    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 ss - 2 * dp[target]


#  494. 目标和 
# 教程给的分析还是很有意思的,目前还是做不出来,还是抄袭答案了
def findTargetSumWays(nums, target):
    ss = sum(nums)
    # 边界条件为target > ss or target < -ss or (ss + target) % 2 == 1
    if abs(target) > ss or (ss + target) % 2 == 1: return 0 
    bagsize = (ss + 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.一和零  
# 还是没搞懂 0-1 背包的范式,感觉还是最开始将题目能转换成背包的模式最重要,反正,还是先抄袭一下答案,等能静下心的时候在处理
def findmaxform(strs, m, n):
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for str in strs:
        ones = str.count('1')
        zeros = str.count('0')
        for i in range(m, zeros - 1, -1):
            for j in range(n, ones - 1, -1):
                dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
    return dp[m][n]


你可能感兴趣的:(代码随想录,python,算法,开发语言)