1049. 最后一块石头的重量 II
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
target = int(sum(stones)/2)
dp = [0] * (target+1)
for i in stones:
for j in range(target ,-1 ,-1):
if j>=i:
dp[j] = max(dp[j],dp[j-i]+i)
# print(dp)
return sum(stones) - 2*dp[target]
494. 目标和
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
# 想象成正组和负组pos -neg = target pos+neg = sum
#dp 数组是正组和为pos的个数
#递推公式是 dp[j] += dp[j-nums[i]]
if abs(target) > sum(nums):
return 0 # 此时没有方案
if (target + sum(nums)) % 2 == 1:
return 0 # 此时没有方案
pos = int((sum(nums) + target)/2)
dp = [0]* (pos+1)
dp[0] =1
for i in nums:
for j in range(pos,-1,-1):
if j>=i:
dp[j] +=dp[j-i]
# print(dp)
return dp[pos]
474. 一和零
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] *(n+1) for _ in range(m+1)]
for s in strs:
nums0=s.count('0')
nums1 = len(s)-nums0
print(nums0)
for i in range(m,nums0-1,-1):
for j in range(n,nums1-1,-1):
dp[i][j] = max(dp[i][j],dp[i-nums0][j-nums1]+1)
return dp[m][n]