赞
踩
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问题进行总结和讨论的文章,我觉得总结得很仔细了。链接如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。