背包型动态规划
BackPack
背包问题要把总承重放入状态。
确定状态:
f[i][m]
f
[
i
]
[
m
]
:
i
i
个物品能不能拼出重量
f[i][m]=f[i−1][m]orf[i−1][m−Ai−1]
f
[
i
]
[
m
]
=
f
[
i
−
1
]
[
m
]
o
r
f
[
i
−
1
]
[
m
−
A
i
−
1
]
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@return: The maximum size
"""
def backPack(self, m, A):
# write your code here
can=[[False]*(m+1) for i in range(len(A)+1)] # 物品*重量
can[0][0]=True
for i in range(1,len(A)+1): # i表示物品
for w in range(m+1): # w表示重量
can[i][w]=can[i-1][w]
if w>=A[i-1]:
can[i][w]=can[i][w] or can[i-1][w-A[i-1]]
for i in range(m,-1,-1):
if can[len(A)][i]==True:
return i
return 0
Backpack V
def numConditions(items,target):
if not items:
return 0
n=len(items)
res=[0]*(target+1)
res[0]=1
#for w in range(1,target+1):
#res[w]=0
for i in range(1,n+1):
for w in range(target,-1,-1):
if w>=items[i-1]:
res[w]=res[w]+res[w-items[i-1]]
return res[-1]
BackPack
class Solution:
"""
@param nums: an integer array and all positive numbers, no duplicates
@param target: An integer
@return: An integer
"""
def backPackVI(self, nums, target):
# write your code here
if not nums:
return 0
res=[0]*(target+1)
res[0]=1
for w in range(1,target+1):
for num in nums:
if w>=num:
res[w]=res[w]+res[w-num]
return res[-1]
BackPack II
确定状态:
f[i][w]
f
[
i
]
[
w
]
前
i
i
个物品能不能拼出重量,如果能此时物品的最大价值为多少。
f[i][w]=max(f[i−1][w],f[i−1][w−Ai−1]+Vi−1|w>=Ai−1,f[i−1][w−Ai−1]≠−1)
f
[
i
]
[
w
]
=
m
a
x
(
f
[
i
−
1
]
[
w
]
,
f
[
i
−
1
]
[
w
−
A
i
−
1
]
+
V
i
−
1
|
w
>=
A
i
−
1
,
f
[
i
−
1
]
[
w
−
A
i
−
1
]
≠
−
1
)
def biggestV(values, weights, maxW):
numItems = len(values)
# maxV=[[0]*(weights+1) for _ in range(numItems+1)] #items*weight
maxV = [0] * (maxW + 1)
maxV[0] = 0
for w in range(1, maxW+ 1):
maxV[w] = -1
for i in range(1, numItems + 1):
for w in range(maxW, -1, -1):
if w >= weights[i - 1] and maxV[w - weights[i - 1]] != -1:
maxV[w] = max(maxV[w], maxV[w - weights[i-1]] + values[i - 1])
res = 0
for w in range(maxW, -1, -1):
if maxV[w] > res:
res = maxV[w]
return res
Backpack III
优化的关键是找重复的步骤。
def biggestV(weights,values,maxW):
if not weights:
return 0
maxV=[0]*(maxW+1)
maxV[0]=0
for w in range(1,maxW+1):
maxV[w]=-1
for i in range(1,len(weights)+1):
for w in range(maxW+1):
if w>=weights[i-1] and maxV[w-weights[i-1]]!=-1:
maxV[w]=max(maxV[w],maxV[w-weights[i-1]]+values[i-1])
res=0
for w in range(1,maxW+1):
res=max(maxV[w],res)
return res