子集和 - 恢复解决方案

时间:2017-02-23 13:38:31

标签: algorithm dynamic sum subset recover

我编写了一个动态编程算法,可以找到总和达到目标值的子集总数。但是,我无法开发恢复解决方案的功能(即打印出实际的子集)。

例如,让我们将 [1,3,5,7,9,10] 设置为目标 13 。 我的算法计算出有3个子集。输出表如下图所示。

output table for my subset sum algorithm

因为这是一个简单的集合,我可以手动确定哪三个子集构成了目标。那就是:

[3,10]
[1,3,9]
[1,5,7]

但是,对于更复杂的解决方案,我如何使用输出表递归恢复解决方案?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

买者

如果没有看到您的算法及其任何输入限制(例如,集合中是否允许重复值?),则可能无法设计出适用于所有可能情况的方法。

但是,似乎以下内容适用于示例结果表中列出的所有情况。如果您发现这对其他情况不起作用,请将这些示例添加到您的问题中。 (我将目标= 0视为一种特殊情况。)

算法草图

按升序迭代目标列的结果。

当结果递增时,您已识别出另一个子集,并且已找到该子集中的最大值。

要查找子集中的剩余值,请“改变”商店店员的方式。换句话说,向后走下设定值,尽可能减去剩余总数。

样本运行

对于给定的例子,对于集合[1,3,5,7,9,10]中的子集,目标和= 13:

resultCount = 0

result(13,1) is 0; this result - resultCount = 0, so no new subsets

result(13,3) is 0; this result - resultCount = 0, so no new subsets

result(13,5) is 0; this result - resultCount = 0, so no new subsets

result(13,7) is 1; this result - resultCount = 1, so resultCount = 1
                                                     and new subset = [7]
                                                     and remaining = 13 - 7 = 6
    5 < 6, so subset = [7,5] and remaining = 6 - 5 = 1
    3 > 1, so remaining is still 1
    1 = 1, so subset = [7,5,1] and remaining = 0 (subset complete)

result(13,9) is 2; this result - resultCount = 1, so resultCount = 2
                                                     and new subset = [9]
                                                     and remaining = 13 - 9 = 4
    7 > 4, so remaining is still 4
    5 > 4, so remaining is still 4
    3 < 4, so subset = [9,3] and remaining = 4 - 3 = 1
    1 = 1, so subset = [9,3,1] and remaining = 1 - 1 = 0 (subset complete)

result(13,10) is 3; this result - resultCount = 1, so resultCount = 3
                                                      and new subset = [10]
                                                      and remaining = 13 - 10 = 3
    9 > 3, so remaining is still 3
    7 > 3, so remaining is still 3
    5 > 3, so remaining is still 3
    3 = 3, so subset = [10,3] and remaining = 3 - 3 = 0 (subset complete)

确定了3个子集的运行结束:

[7,5,1]
[9,3,1]
[10,3]