阅读量:1
动态规划:01背包理论基础(二维)
dp[i][j]含义:
在下标为[0, i]的物品中任取,放进容量为j的背包中,价值总和的最大值
递推公式:
(1)不放物品i,背包容量为j时,所能装的最大价值为:dp[ i -1][j]
(2)放物品i,背包容量为j时,所能装的最大价值:dp[ i -1][ j - weight[i] ] + value[i]
dp[i][j] = max( dp[i-1][j], dp[i-1][ j - weight[i] ]+value[i] )
def test_2_wei_bag_problem1(): weight = [1, 3, 4] value = [15, 20, 30] bagweight = 4 #背包最大重量为4 # 二维数组 dp = [[0] * (bagweight + 1) for _ in range(len(weight))] # 初始化 for j in range(weight[0], bagweight + 1): dp[0][j] = value[0] # weight数组的大小就是物品个数 for i in range(1, len(weight)): # 遍历物品 for j in range(bagweight + 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[len(weight) - 1][bagweight]) test_2_wei_bag_problem1()
动态规划:01背包理论基础(滚动数组)(一维)
在使用二维数组的时候,递推公式:dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
其实可以发现如果把dp[i - 1]那一层拷贝到dp[i]上,表达式完全可以是:dp[i][j] = max(dp[i][j], dp[i][j - weight[i]] + value[i]);
与其把dp[i - 1]这一层拷贝到dp[i]上,不如只用一个一维数组了,只用dp[j](一维数组,也可以理解是一个滚动数组)。
dp[j]含义:
容量为j的背包所能装的最大价值为dp[j]
递推公式:
dp[j] = max( dp[j], dp[j - weight[i]] + value[i] )
遍历顺序:
倒序遍历背包!倒序遍历是为了保证物品i只被放入一次!。但如果一旦正序遍历了,那么物品0就会被重复加入多次!
倒序遍历的原因是,本质上还是一个对二维数组的遍历,并且右下角的值依赖上一层左上角的值,因此需要保证左边的值仍然是上一层的,从右向左覆盖。
def test_1_wei_bag_problem(): weight = [1, 3, 4] value = [15, 20, 30] bagWeight = 4 # 初始化 dp = [0] * (bagWeight + 1) for i in range(len(weight)): # 遍历物品 for j in range(bagWeight, weight[i] - 1, -1): # 遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) print(dp[bagWeight]) test_1_wei_bag_problem()
class Solution: def canPartition(self, nums: List[int]) -> bool: if sum(nums) %2 != 0: return False target = sum(nums) // 2 dp = [0 for _ in range(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]) if dp[-1] == target: return True else: return False