简体   繁体   English

使用递归在 python 中找到最接近的子集和

[英]Using recursion to find closest subset sum in python

I have written some code and it is more of a dynamic programming style.我写了一些代码,它更像是一种动态编程风格。 It could be described similarly to searching for a tree, which is why I would like for my code to be recursive and not make use of python's dictionary, how can this be done?它可以类似于搜索树来描述,这就是为什么我希望我的代码是递归的而不是使用 python 的字典,这怎么能做到?

I can possibly do a recursive sum function, but not a recursive function to do my traceback part.我可以做一个递归和 function,但不能做一个递归 function 来做我的回溯部分。

def closestSum(arr, k):
    #create a dp dictionary to grow. key is closest sum so far, value is the list of numbers that add up to key
    dp_dict = {0:[]}

    for num in arr:
        dict_copy = dict(dp_dict)
        # grow or update the dp dict with the closest sum so far
        for sum in dp_dict:
            if sum + num <= 2* k:
                dict_copy[sum+num] = dp_dict[sum]+[num]
        dp_dict = dict_copy

    #traceback - find the item in dp dict that is closest to k
    result = (k,[])
    for sum, number_list in dp_dict.items():
        distance = abs(k - sum)
        if distance < result[0]:
            result = (distance, number_list)
    return result[1]

# should return [69, 82]
print(closestSum([15, 79, 99, 6, 69, 82, 32], 150))

# should return [12, 91, 47]
print(closestSum([12, 79, 99, 91, 81, 47], 150))
def closest_sum(arr, k, sums):
    if len(arr) == 0:
        return sums
    el = arr.pop()
    if el == k:
        return {0: [el]}
    if not sums:
        return closest_sum(arr, k, {el - k: [el]})

    if el != 0:
        sums.update({s + el: [el] + sums[s] for s in sums if (s < k) == (el > 0)})
    sums[el - k] = [el]
    return closest_sum(arr, k, sums)


res = closest_sum([12, 79, 99, 91, 81, 47], 150, {})
goal = res[min(res, key=abs)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM