Python 动态规划 解决0-1背包问题

参考:http://www.tuicool.com/articles/Fji2Qb;这个博客的在输出选择的物品时有错误!!!运行环境python2.x

代码如下:

#n-供选择的物品个数,c-物品最大承重(就是限制条件),w-每个物品的重量,v-每个物品的价值

def bag(n,c,w,v):
  res=[[-1 for j in range(c+1)] for i in range(n+1)]
  for j in range(c+1):
    res[0][j]=0
  for i in range(1,n+1):
    for j in range(1,c+1):
      res[i][j]=res[i-1][j]
      if j>=w[i-1] and res[i][j]<res[i-1][j-w[i-1]]+v[i-1]:
        res[i][j]=res[i-1][j-w[i-1]]+v[i-1]
  print res
  return res

def show(n,c,w,res):
  print '最大价值为:',res[n][c]
  x=[False for i in range(n)]
  j=c
  for i in range(n,0,-1):
    if res[i][j]>res[i-1][j]:
       x[i-1]=True
       j-=w[i-1]
  print('选择的物品为:')
  for i in range(n):
    if x[i]:
      print '第',i,'个,'
  print('')

if __name__=='__main__':
  n=5
  c=10
  w=[2,2,6,5,4]
  v=[6,3,5,7,6]
  res=bag(n,c,w,v)
  show(n,c,w,res)


输出:[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [-1, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6], [-1, 0, 6, 6, 9, 9, 9, 9, 9, 9, 9], [-1, 0, 6, 6, 9, 9, 9, 9, 11, 11, 14], [-1, 0, 6, 6, 9, 9, 9, 13, 13, 16, 16], [-1, 0, 6, 6, 9, 9, 12, 13, 15, 16, 16]]
最大价值为: 16
选择的物品为:
第 0 个,
第 1 个,
第 3 个,

    原文作者:动态规划
    原文地址: https://blog.csdn.net/baoyan2015/article/details/52788753
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞