完全背包问题
题目链接:
dp=[0]*(bag_size+1)
for i in range(len(weight)):#物品
for j in range(weight[i]-1,bag_size):#背包
dp[j]=max(dp[j],dp[j-weight[i]]+values[i])#价值
# 先遍历背包,再遍历物品
def test_complete_pack2():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
dp = [0]*(bag_weight + 1)
for j in range(bag_weight + 1):
for i in range(len(weight)):
if j >= weight[i]:
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
正序遍历就可以。
518. 零钱兑换 II
题目链接:518. 零钱兑换 II
这是一个完全背包问题,dp[i]的含义就是i元有多少种组合。
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
dp=[0]*(amount+1)
dp[0]=1
for i in range(len(coins)):#遍历价值
for j in range(coins[i],amount+1):#控制dp的数组
dp[j]+=dp[j-coins[i]]
return dp[-1]
377. 组合总和 Ⅳ
题目链接:377. 组合总和 Ⅳ
先遍历容量,在遍历物品得到的是全排列。
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp=[0]*(target+1)
dp[0]=1
for i in range(1,target+1):
for j in nums:
if i>=j:# 容量大于物品重量时更新
dp[i]+=dp[i-j]
return dp[-1]