分割硬币(uva 562)-Python中的递归dp解决方案

时间:2020-06-18 20:49:00

标签: python python-3.x algorithm dynamic-programming knapsack-problem

我正在从uva解决此问题Dividing Coins。该问题是众所周知的0/1背包问题的一个变体。我正在尝试微调0/1背包的实现以解决此问题。我已经使用许多脱机测试用例测试了我的代码,并且工作正常,但是提交代码时出现运行时错误。

当我注释掉那些检查字典中是否找到子问题的结果的行时。我收到时间限制超出错误。

我无法确切说明问题出在哪里。但是,我觉得我没有记住正确的事情。

能否请您看看我的代码并尝试提供帮助?谢谢!

def recSolve(vals, remW, allItm, idx, mem):

    if idx >= allItm or remW <= 0: # remW is the remaining amount the user could get (not exceeding total/2)
        return 0

    # check if it is in mem already
    if (remW, idx) in mem:
        return mem[(remW, idx)]

    # wight of the current item is more than the remaninig weight, skip to the next item
    if vals[idx] > remW:
        return recSolve(vals, remW, len(vals), idx+1, mem)
    else:
        # choose either picking the item or not (maximize the val)
        pickIt = recSolve(vals, remW - vals[idx], len(vals), idx+1, mem) + vals[idx]
        dontPickIt = recSolve(vals, remW, len(vals), idx+1, mem)
        res = max(pickIt, dontPickIt)
        mem[(remW, idx)] = res
        return res

def solve(vals, remW):
    mem = {}
    return recSolve(vals, remW, len(vals), 0, mem)

def takeInput():
    for i in range(int(input())):
        leng = input() # not used
        coins = input() 
        vals = [int(i) for i in coins.split(' ')] # the coins
        tot_w = sum(vals) 
        res= solve(vals, tot_w//2)  # maximizing the summation while not exceeding totalCoins/2
        print(tot_w - res - res) # getting the difference

takeInput()

0 个答案:

没有答案