一、多重背包理论基础:
有N种物品和一个容量为V 的背包。第i种物品最多有Mi件可用,每件耗费的空间是Ci ,价值是Wi 。求解将哪些物品装入背包可使这些物品的耗费的空间 总和不超过背包容量,且价值总和最大。
其实就是变相的01背包问题。
二、刷题:
1.卡码网 56. 携带矿石资源(第八期模拟笔试)(medium)
解决:
In_nc = input().split()
C = int(In_nc[0])
N = int(In_nc[1])
weights = list(map(int,input().strip().split()))
values = list(map(int,input().strip().split()))
k_s = list(map(int,input().strip().split()))
dp = [0]*(C+1)
for i in range(N):for j in range(C,weights[i] - 1,-1):for k in range(1,min(k_s[i],j//weights[i])+1):dp[j] = max(dp[j],dp[j-k*weights[i]]+k*values[i])
print(dp[C])
2.leetcode题目 198. 打家劫舍 - 力扣(LeetCode)(medium)
解决:
class Solution:def rob(self, nums: List[int]) -> int:if not nums:return 0if len(nums)==1:return nums[0]dp = [0]*(len(nums))dp[0] = nums[0]dp[1] = max(nums[1],nums[0])for i in range(2,len(nums)):dp[i] = max(dp[i-1],dp[i-2] + nums[i])return dp[len(nums)-1]
3.leetcode题目 213. 打家劫舍 II - 力扣(LeetCode)(medium)
解决:
class Solution:def rob(self, nums: List[int]) -> int:def robrange(nums,start,end):first = nums[start]second = max(nums[start],nums[start+1])for i in range(start+2,end+1):first,second = second,max(second,first+nums[i])return secondif not nums:return 0elif len(nums) == 1:return nums[0]elif len(nums) == 2:return max(nums[0],nums[1])else:return max(robrange(nums,0,len(nums)-2),robrange(nums,1,len(nums)-1))
4.leetcode题目 337. 打家劫舍 III - 力扣(LeetCode)(medium)
此题为树形dp
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def rob(self, root: Optional[TreeNode]) -> int:def dfs(root):if not root:return 0,0la,lb = dfs(root.left)ra,rb = dfs(root.right)return root.val + lb + rb,max(la,lb) + max(ra,rb)return max(dfs(root))