背包问题模板
列为物品 行为maxsize
看在maxsize的情况下放与不放物体的最大value
def beibao(weight,value,size):
dp=[[0]*(size+1) for _ in range(weight)]
for j in range(weight[0],size+1):
dp[0][j]=value[0]
for i in range(1,len(weight)):
for j in range(size+1):
if j<weight[i]:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=max(dp[i-1][j],dp[i-1][j-weight]+value[i])
return dp[-1][-1]
滚动数组版:依次看什么时候放物品 注意从后往前 物品只有一个 从最宽敞的放 否则会放多次
def 01beibao(weight,value,size):
dp=[0]*(size+1)
for i in range(len(weight)):
for j in range(size,weight[i]-1,-1):(weight-1之前的放不进去 不改)
dp[j]=max(dp[j],dp[j-weight[i]]+value[i])
return dp[-1]
以sum的一半做01背包
class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums)%2: return False
target=sum(nums)//2
dp=[0]*(target+1)
for num in nums:
for j in range(target,num-1,-1):
dp[j]=max(dp[j],dp[j-num]+num)
return dp[-1]==target