def weight_bag_problem(bag_size,weight,value):
m = len(weight)
n = bag_size + 1
dp = [[0] * n for _ in range(m)]
#初始化
for a in range(weight[0],bag_size+1):
dp[0][a] = value[0]
for b in range(m):
dp[b][0] = 0
#遍历顺序(先物品后容量)
for i in range(m):
for j in range(n):
if weight[i] > j:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = max(dp[i-1][j],dp[i-1][j-weight[i]]+value[i])
return dp
01背包问题 一维
#一维数组
def test_1_wei_bag_problem(bag_size,weight,value):
m = len(weight)
n = bag_size+1
dp = [0] * n
for i in range(m):
for j in range(n-1,weight[i]-1,-1):
print(dp)
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
return dp
416. 分割等和子集
class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)
if target % 2 != 0: return False
target = target //2
#既是价值也是重量
dp = [0] * (target+1)
for i in range(len(nums)):
for j in range(target,nums[i] -1 , -1):
dp[j] = max(dp[j],dp[j-nums[i]]+nums[i])
return dp[-1] == target