Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
Thoughts
A typical k-sum problem. Time is N to the power of (k-1).
Java Solution
Here is the hashCode method of ArrayList. It makes sure that if all elements of two lists are the same, then the hash code of the two lists will be the same. Since each element in the ArrayList is Integer, same integer has same hash code.
本文转载自:
http://www.programcreek.com/2013/02/leetcode-4sum-java/
结合之前的2sum和3sum,可以推断可以通过不断降维迭代来实现。这可以引申出K-sum的问题。
这里有一篇对sum问题进行总结和讨论的文章,我觉得总结得很仔细了。链接如下:
本文针对4Sum问题进行了详细的解析,并提供了有效的解决方案。该问题要求在给定数组中找到四个数的组合,使得它们的和等于目标值。文章还讨论了如何通过降维迭代的方法解决更一般的K-Sum问题。
1446

被折叠的 条评论
为什么被折叠?



