-
今日学习的文章链接,或者视频链接
-
自己看到题目的第一想法
-
看完代码随想录之后的想法
01背包:
def test_2_wei_bag_problem1(bag_size, weight, value) -> int:
rows, cols = len(weight), bag_size + 1
dp = [[0 for _ in range(cols)] for _ in range(rows)]
# 初始化dp数组.
for i in range(rows):
dp[i][0] = 0
first_item_weight, first_item_value = weight[0], value[0]
for j in range(1, cols):
if first_item_weight <= j:
dp[0][j] = first_item_value
# 更新dp数组: 先遍历物品, 再遍历背包.
for i in range(1, len(weight)):
cur_weight, cur_val = weight[i], value[i]
for j in range(1, cols):
if cur_weight > j: # 说明背包装不下当前物品.
dp[i][j] = dp[i - 1][j] # 所以不装当前物品.
else:
# 定义dp数组: dp[i][j] 前i个物品里,放进容量为j的背包,价值总和最大是多少。
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight]+ cur_val)
print(dp)
'''
if __name__ == "__main__":
bag_size = 4
weight = [1, 3, 4]
value = [15, 20, 30]
test_2_wei_bag_problem1(bag_size, weight, value)
'''
一维dp数组:
def test_1_wei_bag_problem():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
# 初始化: 全为0
dp = [0] * (bag_weight + 1)
# 先遍历物品, 再遍历背包容量
for i in range(len(weight)):
for j in range(bag_weight, weight[i] - 1, -1):
# 递归公式
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp)
test_1_wei_bag_problem()
416:
一维dp:
class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)
if target % 2 == 1: return False
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 target == dp[target]
二维dp:
class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)
nums = sorted(nums)
# 做最初的判断
if target % 2 != 0:
return False
# 找到 target value 可以认为这个是背包的体积
target = target // 2
row = len(nums)
col = target + 1
# 定义 dp table
dp = [[0 for _ in range(col)] for _ in range(row)]
# 初始 dp value
for i in range(row):
dp[i][0] = 0
for j in range(1, target):
if nums[0] <= j:
dp[0][j] = nums[0]
# 遍历 先遍历物品再遍历背包
for i in range(1, row):
cur_weight = nums[i]
cur_value = nums[i]
for j in range(1, col):
if cur_weight > j:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight] + cur_value)
# 输出结果
return dp[-1][-1] == target
-
自己实现过程中遇到哪些困难
-
今日收获,记录一下自己的学习时长