背包问题knapsack与动态编程

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值