背包问题knapsack与动态编程
来源:互联网 发布:mac飞秋下载 编辑:程序博客网 时间:2024/05/17 03:27
def maxVal(w, v, i, aW):
global numCalls
numCalls += 1
print numCalls, 'maxVal called with: ', i, aW
if i == 0:
if w[i] <= aW: return v[i]
else: return 0
without_i = maxVal(w, v, i-1, aW)
if w[i] > aW:
return without_i
else:
with_i = v[i] + maxVal(w, v, i-1, aW - w[i])
return max(with_i, without_i)
def fastMaxVal(w, v, i, aW, m):
global numCalls
numCalls += 1
## print numCalls, 'fastMaxVal called with: ', i, aW
try: return m[(i, aW)]
except KeyError:
if i == 0:
if w[i] <= aW: return v[i]
else: return 0
without_i = fastMaxVal(w, v, i-1, aW, m)
if w[i] > aW:
return without_i
else:
with_i = v[i] + fastMaxVal(w, v, i-1, aW - w[i], m)
res = max(with_i, without_i)
m[(i, aW)] = res
return res
def maxVal0(w, v, i, aW):
m = {}
return fastMaxVal(w, v, i, aW, m)
##weights = [1, 5, 3, 4]
##vals = [15, 10, 9, 5]
##numCalls = 0
##res = maxVal(weights, vals, len(vals) - 1, 8)
##print 'max Val =', res, 'number of calls = ', numCalls
maxWeight = 40
w = [5,5,1,8,2,4,7,5,2,8,1,2,7,3,5,7,8,5,5,8,2,3,8,4,9]
v = [5,5,3,5,6,7,2,3,7,1,6,3,6,8,8,6,5,6,8,4,3,3,2,3,4]
numCalls = 0
res = maxVal0(w, v, len(v) - 1, maxWeight)
print 'max Val =', res, 'number of calls = ', numCalls
- 背包问题knapsack与动态编程
- 背包问题knapsack
- 背包问题(Knapsack problem)
- Knapsack Problem|背包问题
- 背包问题 (Knapsack.cpp)
- 动态规划之背包问题(knapsack算法)
- 动态规划解背包问题/C++/Knapsack problem
- 动态规划解背包问题/C++/Knapsack problem
- 01Knapsack(01背包问题)
- DP:背包问题 Knapsack Problem
- knapsack problems(背包问题)
- 0-1背包问题(knapsack problem)
- Algorithm Gossip:背包问题(Knapsack Problem)
- 背包问题(Knapsack problem)之01
- Algorithm Gossip: 背包问题(Knapsack Problem)
- 背包问题(Knapsack problem) 之二
- Algorithm Gossip: 背包问题(Knapsack Problem)
- <<c>>背包问题(Knapsack)
- Android上使用XML---SAX解析器(转)
- poj -- 2155 Matrix (二维树状数组)
- 如何设置使windows(dos)命令中目录和文件可以自动完成和补齐
- LINQ To Xml:使用XPath
- PHP+MYSQL-操作数据库案例1
- 背包问题knapsack与动态编程
- netfilter框架分析
- PHP+MYSQL-面向对象-操作数据库案例
- 一则新闻片段和一个短书摘
- 敏捷开发环境下的领导技能问题
- log4net 使用示例|using log4net with asp.net/winform
- WCF常见问题(2) -- Winform Host UI阻塞
- swfupload 多文件上传的属性与事件方法总结
- 敏捷开发不利于架构设计?