其他分享
首页 > 其他分享> > 子集一个列表以添加到另一个列表中的元素

子集一个列表以添加到另一个列表中的元素

作者:互联网

有没有人对使用python解决以下问题的优雅代码和数学有任何想法?

我有两个数字列表:

A=[83.4,108,-240.2]
B=[10.3,96.7,-5.5,-20.4,30.9,2.1,-6.1,51.5,37.7,-25,-10.7,-250.4,-14.2,56.4,-11.5,163.9,-146.6,-2.6,7.9,-13.2]

我知道B可以分为三个包含B元素的列表,这样三个列表一起包含B中的所有元素,但是三个列表没有重叠的元素.这三个列表的总和将等于A中的三个元素.

我可以使用蛮力方法,即将B元素的所有可能组合创建为三组,但是随着B中元素的数量,可能性的数量会迅速增加.我还研究了背包问题,但这似乎只需要正值.

解决方法:

这确实是subset sum problem的变体:

In 07001, the subset sum problem is one of the important problems in 07002 and 07003. The problem is this: given a set (or multiset) of integers, is there a non-empty subset whose sum is zero? For example, given the set {−7, −3, −2, 5, 8}, the answer is yes because the subset {−3, −2, 5} sums to zero. The problem is 07004.

An equivalent problem is this: given a set of integers and an integer s, does any non-empty subset sum to s?

证明它是NP完整的:

The easiest way to prove that some new problem is NP-complete is first to prove that it is in NP, and then to reduce some known NP-complete problem to it.

它在NP中,因为可以在多项式时间内进行验证:给定一个潜在的解决方案,只需将子集中的数字相加,然后查看它们是否与A中的数字相对应.并且,您可以将子集问题简化为多项式中的该问题时间:给定集合x和目标和s,令A = [s,sum(x)-s]和B = x.

它是NP-complete,在一般情况下,无法使用Python或其他方式快速解决此问题:

Although any given solution to an NP-complete problem can be verified quickly (in polynomial time), there is no known efficient way to locate a solution in the first place; indeed, the most notable characteristic of NP-complete problems is that no fast solution to them is known. That is, the time required to solve the problem using any currently known 07006 increases very quickly as the size of the problem grows. As a consequence, determining whether or not it is possible to solve these problems quickly, called the 07007, is one of the principal 07008 today.

标签:subset-sum,python,math
来源: https://codeday.me/bug/20191119/2038296.html