1049.最后一块石头的重量II
最后一块石头的重量->将一堆石头分为两堆,求使得两堆重量最小差值->使得两堆石头的重量接近sum(stones)//2
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.目标和
dp二维数组解法
时间复杂度:O(n*capcity
空间复杂度:O(n*capcity
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
""" pos + neg = total """
""" pos - neg = target """
total = sum(nums)
# 提示中target可能为负数,此时对于非负整数nums 无法获得目标和 返回0
if abs(target) > total:
return 0
# 因为pos = (total - target) // 2
if (total + target)%2 != 0:
return 0
pos = (total + target)//2
neg = (total - target)//2
# 选择的pos和neg中的较小者使得dp空间最小
capcity = min(pos,neg)
n = len(nums)
# 初始化
dp = [[0]*(capcity+1)for _ in range(n+1)]
# dp[i][j]表示选择前i个数字中选出若干个其和为j的方案数量
dp[0][0] = 1
# 状态更新
for i in range(1,n+1):
for j in range(capcity+1):
# 若j容量有限无法选择第i个数字nums[i-1]
if j < nums[i-1]:
dp[i][j] = dp[i-1][j]
else:
# 选或不选择
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]]
# 在前n个数字中选择了容量为capcity的方案数量
return dp[n][capcity]
滚动数组
时间复杂度:O(n*capcity
空间复杂度:O(n*capcity
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
""" pos + neg = total """
""" pos - neg = target """
total = sum(nums)
# 提示中target可能为负数,此时对于非负整数nums 无法获得目标和 返回0
if abs(target) > total:
return 0
# 因为pos = (total - target) // 2
if (total + target)%2 != 0:
return 0
pos = (total + target)//2
neg = (total - target)//2
# 选择的pos和neg中的较小者使得dp空间最小
capcity = min(pos,neg)
n = len(nums)
# 初始化
dp = [0] * (capcity+1)
dp[0] = 1
for i in range(1,n+1):
dp2 = [0]*(capcity+1)
for j in range(capcity+1):
if j <nums[i-1]:
dp2[j] = dp[j]
else:
dp2[j] = dp[j]+dp[j-nums[i-1]]
dp = dp2
return dp[capcity]
一维数组内存循环倒叙
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
""" pos + neg = total """
""" pos - neg = target """
total = sum(nums)
# 提示中target可能为负数,此时对于非负整数nums 无法获得目标和 返回0
if abs(target) > total:
return 0
# 因为pos = (total - target) // 2
if (total + target)%2 != 0:
return 0
pos = (total + target)//2
neg = (total - target)//2
# 选择的pos和neg中的较小者使得dp空间最小
capcity = min(pos,neg)
n = len(nums)
# 初始化
dp = [0] * (capcity+1)
dp[0] = 1
for num in nums:
# # 内层循环倒序,且j>=num 【j<num时无需更新dp[j]】
for j in range(capcity,num-1,-1):
dp[j] += dp[j-num]
return dp[capcity]
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:
ones = s.count('1')
zeros = s.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]