接上一篇,同样的01背包问题,上一篇采用动态规划的方法,现在用回溯法解决。回溯法采用深度优先策略搜索问题的解,不多说,代码如下:
bestV=0 curW=0 curV=0 bestx=None def backtrack(i): global bestV,curW,curV,x,bestx if i>=n: if bestV<curV: bestV=curV bestx=x[:] else: if curW+w[i]<=c: x[i]=True curW+=w[i] curV+=v[i] backtrack(i+1) curW-=w[i] curV-=v[i] x[i]=False backtrack(i+1) if __name__=='__main__': n=5 c=10 w=[2,2,6,5,4] v=[6,3,5,4,6] x=[False for i in range(n)] backtrack(0) print(bestV) print(bestx)
运行结果如下:
转载请注明:转自http://blog.csdn.net/littlethunder/article/details/26621427