Python动态规划计算0-1背包问题的最优值

from pprint import pprint as pp
def KnapSack(weight,value,capacity):   #计算最优值
    n=len(weight)-1
    m=[]
#初始化列表m,m[i][j]表示背包容量为j,可选物品为,,i+1...n时的最优值
    for i in range(0,n+1):   
        m.append([])
        for j in range(0,capacity+1):
            m[i].append([])

##########计算最优值######################################   
    tmpCapacity=min(weight[n],capacity)
    for j in range(0,tmpCapacity):
        m[n][j]=0
    for j in range(tmpCapacity,capacity+1):
        m[n][j]=value[n]
    for i in range(n-1,-1,-1):
        tmpCapacity=min(weight[i],capacity)
        for j in range(0,tmpCapacity):
            m[i][j]=m[i+1][j]  
        for j in range(tmpCapacity,capacity+1):
            m[i][j]=max(m[i+1][j],m[i+1][j-weight[i]]+value[i])
########输出结果##########################################
    print 'goods:'
    Traceback(m,weight,capacity) #输出最优解
    print 'MaxValue:',m[0][capacity-1] #打印出最优值
    for i in range(0,n+1):     #打印列表m
        print m[i]

 def Traceback(m,weight,capacity):#依据最优值构造最优解
    goods=[]
    length=len(weight)
    for i in range(0,length-1):
        if  m[i][capacity]==m[i+1][capacity]:
            goods.append(0)
        else:
            goods.append(1)
            capacity=capacity-weight[i]
    if  capacity1][capacity]:
         goods.append(0)
    else:
        goods.append(1)
    print goods

def main():
    weight=[2,2,6,5,4]
    value=[6,3,5,4,6]
    c=10    #测试数据
    KnapSack(weight,value,c)

main()`这里写代码片`

你可能感兴趣的:(算法)