赞
踩
视频讲解:https://www.bilibili.com/video/BV1uK411o7c9
https://programmercarl.com/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85.html
装第i个物品
和 不装第i个物品
两种情况里的较大值dp[j - weight[i]] + value[i]
,weight[i]表示第i个物品的重量,value[i]代表第i个物品的价值dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
# 一维数组解法
# m种物品,背包容量为n,每个物品的重量和价值分别保存在weight和value里
dp = [0] * (n + 1)
for i in range(1, m):
for j in range(1, n + 1):
if (j - weight[i]) >= 0:
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp[-1])
视频讲解:https://www.bilibili.com/video/BV1KM411k75j
https://programmercarl.com/0518.%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2II.html
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount + 1)
dp[0] = 1
for i in range(len(coins)):
for j in range(1, amount + 1):
if j >= coins[i]:
dp[j] += dp[j - coins[i]]
return dp[-1]
视频讲解:https://www.bilibili.com/video/BV1V14y1n7B6
https://programmercarl.com/0377.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C%E2%85%A3.html
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0] * (target + 1)
dp[0] = 1
for j in range(1, target + 1):
for i in range(len(nums)):
if j >= nums[i]:
dp[j] += dp[j - nums[i]]
return dp[-1]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。