题目链接:46. 携带研究材料(第六期模拟笔试) (kamacoder.com)
二维dp思路
m, n = map(int,input().split())
weight = list(map(int,input().split()))
value = list(map(int, input().split()))
dp = [[0] * (n + 1) for _ in range(m)]
for j in range(weight[0], n + 1):
dp[0][j] = value[0]
for i in range(1, m):#遍历物品
for j in range(n + 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[i]] + value[i])
print(dp[m-1][n])
一维dp思路
m, n = map(int,input().split())
weight = list(map(int,input().split()))
value = list(map(int, input().split()))
dp = [0] * (n + 1)
for i in range(m):
for j in range(n, weight[i]-1, -1):
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp[n])
题目链接:416. 分割等和子集 - 力扣(LeetCode)
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
sum_num = 0
dp = [0] * 10001
for i in range(len(nums)):
sum_num += nums[i]
if sum_num % 2 != 0: #无法分成等和子集
return False
target = sum_num // 2
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])
if dp[target] == target: #如果此时dp[target] = target 也就说明集合中的元素刚好可以凑成总和target 则代表
return True
else:
return False