一、完全背包理论基础:
完全背包和01背包问题唯一不通过的地方就是,每种物品有无限件。
二、刷题:
1.卡码网 52. 携带研究材料(第七期模拟笔试) (kamacoder.com)(medium)
解决:
nv = input().strip().split()
N = int(nv[0])
V = int(nv[1])
weights = []
values = []
for tcase in range(N):weight,value = map(int,input().split())weights.append(weight)values.append(value)
dp = [0]*(V+1)
for i in range(N):for j in range(weights[i],V+1):dp[j] = max(dp[j],dp[j-weights[i]] + values[i])
print(dp[V])
2.leetcode题目 518. 零钱兑换 II - 力扣(LeetCode)(medium)
解决:
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(coins[i],amount + 1):dp[j] += dp[j-coins[i]]return dp[amount]
3.leetcode题目 377. 组合总和 Ⅳ - 力扣(LeetCode)
解决:
class Solution:def combinationSum4(self, nums: List[int], target: int) -> int:dp = [0]*(target + 1)dp[0] = 1for i in range(1,target+1):for j in range(len(nums)):if i >=nums[j]:dp[i] += dp[i-nums[j]]return dp[target]
4.卡码网 57. 爬楼梯(第八期模拟笔试) (kamacoder.com)
解决:
a= input().split()
n = int(a[0])
m = int(a[1])
dp = [0]*(n+1)
dp[0] = 1
for i in range(1,n+1):for j in range(1,m+1):if i>=j:dp[i] += dp[i-j]
print(dp[n])