如何最佳地将数组划分为两个子数组,以使两个子数组中的元素之和相同,否则会出错?
如何最佳地将数组划分为两个子数组,以使两个子数组中的元素之和相同,否则给出错误?
示例 1
给定数组
10, 20 , 30 , 5 , 40 , 50 , 40 , 15
它可以被划分为
10, 20, 30, 5, 40
并且
50, 40, 15
每个子数组的总和为 105。
示例 2
10, 20, 30, 5, 40, 50, 40, 10
该数组不能分为 2 个总和相等的数组。
How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?
Example 1
Given the array
10, 20 , 30 , 5 , 40 , 50 , 40 , 15
It can be divided as
10, 20, 30, 5, 40
and
50, 40, 15
Each subarray sums up to 105.
Example 2
10, 20, 30, 5, 40, 50, 40, 10
The array cannot be divided into 2 arrays of an equal sum.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
存在一个涉及动态规划的解决方案,其运行时间为
O(n*TotalSum)
,其中n
是数组中的元素数量,TotalSum< /code> 是它们的总和。
第一部分包括计算可以通过向数组添加元素来创建的所有数字的集合。
对于大小为
n
的数组,我们将其称为T(n)
,(正确性的证明是通过归纳法来证明的,就像大多数递归函数一样。)
此外,记住动态矩阵中的每个单元格,为了创建它而添加的元素。
简单的复杂性分析将表明这是在
O(n*TotalSum)
内完成的。计算
T(n)
后,在集合中搜索恰好等于TotalSum / 2
大小的元素。如果存在这样的项目,则创建它的元素加在一起等于
TotalSum / 2
,并且不属于其创建的元素也等于TotalSum / 2
(TotalSum - TotalSum / 2 = TotalSum / 2
)。这是一个伪多项式解。 AFAIK,这个问题不知道在 P 中。
There exists a solution, which involves dynamic programming, that runs in
O(n*TotalSum)
, wheren
is the number of elements in the array andTotalSum
is their total sum.The first part consists in calculating the set of all numbers that can be created by adding elements to the array.
For an array of size
n
, we will call thisT(n)
,(The proof of correctness is by induction, as in most cases of recursive functions.)
Also, remember for each cell in the dynamic matrix, the elements that were added in order to create it.
Simple complexity analysis will show that this is done in
O(n*TotalSum)
.After calculating
T(n)
, search the set for an element exactly the size ofTotalSum / 2
.If such an item exists, then the elements that created it, added together, equal
TotalSum / 2
, and the elements that were not part of its creation also equalTotalSum / 2
(TotalSum - TotalSum / 2 = TotalSum / 2
).This is a pseudo-polynomial solution. AFAIK, this problem is not known to be in P.
这称为分区问题。对于一些特殊情况有最优的解决方案。然而,一般来说,这是一个NP完全问题。
This is called partition problem. There are optimal solutions for some special cases. However, in general, it is an NP-complete problem.
在其常见变体中,这个问题施加了 2 个约束,并且可以通过更简单的方式来完成。
然后起作用的算法可能是:
以下代码执行上述操作:
输出:
当然,如果元素可以无序组合,那么它确实会变成具有所有复杂性的分区问题。
In its common variant, this problem imposes 2 constraints and it can be done in an easier way.
The algorithm that then works could be:
The following code does the above:
The output:
Ofcourse, if the elements can be combined out-of-order, it does turn into the partition problem with all its complexity.
这个问题说的是,如果一个数组可以有两个子数组,并且它们的元素和相同。
所以应该返回一个布尔值。
我找到了一个有效的算法:
算法:程序
第一步:取一个空数组作为容器,将初始数组排序并保留在空数组中。
步骤2:现在取两个可动态分配的数组,从辅助数组中取出最高和第二高分别保存在两个子数组中,并从辅助数组中删除。
步骤3:比较子数组中元素的总和,总和较小的子数组将有机会获取数组中剩余的最大元素,然后从容器中删除。
步骤4:循环执行步骤3,直到容器为空。
步骤 5:比较两个子数组的总和,如果相同则返回 true,否则返回 false。
// 这个问题的复杂性在于可能有多种组合,但这个算法有一种独特的方式。
This Problem says that if an array can have two subarrays with their sum of elements as same.
So a boolean value should be returned.
I have found an efficient algorithm :
Algo: Procedure
Step 1: Take an empty array as a container , sort the initial array and keep in the empty one.
Step 2: now take two dynamically allocatable arrays and take out highest and 2nd highest from the auxilliary array and keep it in the two subarrays respectively , and delete from the auxiliary array.
Step 3: Compare the sum of elements in the subarrays , the smaller sum one will have chance to fetch highest remaining element in the array and then delete from the container.
Step 4: Loop thru Step 3 until the container is empty.
Step 5: Compare the sum of two subarrays , if they are same return true else false.
// The complexity with this problem is that there may be many combinations possible but this algo has one unique way .
尝试了不同的解决方案。除了 Wiki 解决方案(分区问题)之外。
我已经测试过。 (它适用于大于 0 的正数)如果有人遇到问题,请告诉我。
Tried a different solution . other than Wiki solutions (Partition Problem).
I have tested. ( It works well with positive number greater than 0) please let me know if any one face issue.
这是问题的递归解决方案,一种非递归解决方案可以使用辅助方法在 for 循环中获取索引 0 到当前索引的总和,另一种解决方案可以获取同一当前索引到最后,有效。现在,如果您想将元素放入数组并比较总和,首先找到标记溢出的点(索引),其中两侧的总和相等,然后获取一个列表并在该索引和另一个列表之前添加值在该索引之后。
这是我的(递归),它仅确定是否有地方可以分割数组,以便一侧的数字之和等于另一侧的数字之和。担心indexOutOfBounds,这在递归中很容易发生,一个轻微的错误可能会致命并产生大量异常和错误。
This is a recursive solution to the problem, one non recursive solution could use a helper method to get the sum of indexes 0 to a current index in a for loop and another one could get the sum of all the elements from the same current index to the end, which works. Now if you wanted to get the elements into an array and compare the sum, first find the point (index) which marks the spilt where both side's sum are equal, then get a list and add the values before that index and another list to go after that index.
Here's mine (recursion), which only determines if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side. Worry about indexOutOfBounds, which can easily happen in recursion, a slight mistake could prove fatal and yield a lot of exceptions and errors.
找到解决方案此处
Found solution here
如果总和为偶数,此 Python3 函数会将数字列表拆分并平衡为两个总和相等的单独列表。
This Python3 function will split and balance a list of numbers to two separate lists equal in sum, if the sum is even.
python中的非最优解决方案,
A non optimal solution in python,
其 O(n) 时间和 O(n) 空间
Its O(n) time and O(n) space
首先,如果元素是整数,请检查总数是否能被二整除——如果不是,则不可能成功。
我会将问题设置为二叉树,级别 0 决定元素 0 进入哪个集合,级别 1 决定元素 1 进入哪个集合,依此类推。在任何时候,如果一组的总和是总数的一半,那么你'重新完成-成功。任何时候,如果一组的总和超过总数的一半,则该子树失败,您必须备份。这时候就是一个树遍历问题了。
First, if the elements are integers, check that the total is evenly divisible by two- if it isn't success isn't possible.
I would set up the problem as a binary tree, with level 0 deciding which set element 0 goes into, level 1 deciding which set element 1 goes into, etc. At any time if the sum of one set is half the total, you're done- success. At any time if the sum of one set is more than half the total, that sub-tree is a failure and you have to back up. At that point it is a tree traversal problem.
// 贪婪方法 //
// The Greedy approach //
我在采访中被问到这个问题,我给出了以下简单的解决方案,因为我之前没有在任何网站上看到过这个问题。
假设数组 A = {45,10,10,10,10,5}
然后,分割将在索引 = 1(基于 0 的索引)处进行,这样我们就有两个相等的总和集 {45} 和 {10,10,10,10,5}
/*
将两个索引指针移向数组的中间,直到 currentRightIndex != currentLeftIndex。如果左侧元素之和仍然小于或等于'rightIndex'右侧元素之和,则增加leftIndex。最后,检查是否leftSum == rightSum。如果为 true,我们得到的索引为 currentLeftIndex+1(或简单地 currentRightIndex,因为在这种情况下 currentRightIndex 将等于 currentLeftIndex+1)。
*/
I was asked this question in an interview, and I gave below simple solution, as I had NOT seen this problem in any websiteS earlier.
Lets say Array A = {45,10,10,10,10,5}
Then, the split will be at index = 1 (0-based index) so that we have two equal sum set {45} and {10,10,10,10,5}
/*
Move the two index pointers towards mid of the array untill currentRightIndex != currentLeftIndex. Increase leftIndex if sum of left elements is still less than or equal to sum of elements in right of 'rightIndex'.At the end,check if leftSum == rightSum. If true, we got the index as currentLeftIndex+1(or simply currentRightIndex, as currentRightIndex will be equal to currentLeftIndex+1 in this case).
*/
@Gal Subset-Sum 问题是 NP 完全问题,并且具有 O(n*TotalSum) 伪多项式动态规划算法。但这个问题不是NP完全问题。这是一个特殊情况,实际上可以在线性时间内解决。
在这里,我们正在寻找一个索引,可以将数组分成具有相同总和的两部分。
检查以下代码。
分析:O(n),因为该算法仅迭代数组并且不使用TotalSum。
@Gal Subset-Sum problem is NP-Complete and has a O(n*TotalSum) pseudo-polynomial Dynamic Programming algorithm. But this problem is not NP-Complete. This is a special case and in fact this can be solved in linear time.
Here we are looking for an index where we can split the array into two parts with same sum.
Check following code.
Analysis: O(n), as the algorithm only iterates through the array and does not use TotalSum.
算法:
步骤 1) 将数组分成两部分
步骤2)如果总和相等,则分割完成
步骤 3) 将 array1 中的一个元素与 array2 交换,遵循以下四个规则:
如果 array1 中的元素之和小于 array2 中的元素之和
规则1:
在 array1 中找到一个小于 array2 中的数字,方法是交换
这些元素不会将 array1 的总和增加到超出预期总和。如果找到,则交换
元素并返回。
规则2:
如果不满足Rule1,则在array1中查找比array2中的数字大的数字
这样 array1 和 array2 中任意两个数的差不小于
这两个数字之间的差异。
其他
规则3:
在 array1 中找到一个比 array2 中的数字大的数字,通过交换这些数字
元素,不要将 array1 的总和减少到超出预期总和。如果找到,则交换
元素并返回。
规则4:
如果不满足Rule3,则在array1中查找小于array2中的数字
这样 array1 和 array2 中任意两个数的差不小于
这两个数字之间的差异。
步骤 5) 转到步骤 2,直到交换结果得到一个已遇到相同元素集的数组
Setp 6) 如果发生重复,则该数组不能分成总和相等的两半。当前的数组集合或在此重复之前形成的数组应该是数组的最佳分割。
注意:所采取的方法是将元素从一个数组交换到另一个数组,以使所得总和尽可能接近预期总和。
java 程序位于 Java 代码
Algorithm:
Step 1) Split the array into two
Step 2) If the sum is equal, split is complete
Step 3) Swap one element from array1 with array2, guided by the four rules:
IF the sum of elements in array1 is less than sum of elements in array2
Rule1:
Find a number in array1 that is smaller than a number in array2 in such a way that swapping of
these elements, do not increase the sum of array1 beyond the expected sum. If found, swap the
elements and return.
Rule2:
If Rule1 is not is not satisfied, Find a number in array1 that is bigger than a number in array2 in
such a way that the difference between any two numbers in array1 and array2 is not smaller than
the difference between these two numbers.
ELSE
Rule3:
Find a number in array1 that is bigger than a number in array2 in such a way that swapping these
elements, do not decrease the sum of array1 beyond the expected sum. If found, swap the
elements and return.
Rule4:
If Rule3 is not is not satisfied, Find a number in array1 that is smaller than a number in array2 in
such a way that the difference between any two numbers in array1 and array2 is not smaller than
the difference between these two numbers.
Step 5) Go to Step2 until the swap results in an array with the same set of elements encountered already
Setp 6) If a repetition occurs, this array cannot be split into two halves with equal sum. The current set of arrays OR the set that was formed just before this repetition should be the best split of the array.
Note: The approach taken is to swap element from one array to another in such a way that the resultant sum is as close to the expected sum.
The java program is available at Java Code
请尝试这个,如果不起作用请告诉我。希望它会对您有所帮助。
}
Please try this and let me know if not working. Hope it will helps you.
}
解决此问题的一种糟糕的贪婪启发式方法是:尝试将列表从最小到最大排序,然后通过让 list1 = 奇数元素和 list2 = 偶数元素将该列表分成两部分。
A BAD greedy heuristic to solve this problem: try sorting the list from least to greatest, and split that list into two by having list1 = the odd elements, and list2 = the even elements.
非常简单的递归解决方案
very simple solution with recursion
https://github.com/ShubhamAgrahari/DRjj/blob/master/Subarray_Sum。 java
https://github.com/ShubhamAgrahari/DRjj/blob/master/Subarray_Sum.java