完全背包比0-1背包就改变了遍历顺序,先物品再背包的顺序不再重要,另外遍历背包时不需要从后往前遍历
def test_CompletePack():
weight = [1, 3, 4]
value = [15, 20, 30]
bagWeight = 4
dp = [0] * (bagWeight + 1)
for i in range(len(weight)): # 遍历物品
for j in range(weight[i], bagWeight + 1): # 遍历背包容量
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp[bagWeight])
test_CompletePack()
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount +1)
dp[0] =1
for i in coins:
for j in range(i,amount+1):
dp[j] += dp[j-i]
return dp[amount]
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0] * (target +1)
dp[0] =1
for j in range(target+1):
for i in nums:
if j>=i:
dp[j] += dp[j-i]
return dp[target]