当前位置:   article > 正文

LeetCode – 4Sum (Java)题解

LeetCode – 4Sum (Java)题解

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问题进行总结和讨论的文章,我觉得总结得很仔细了。链接如下:

http://www.sigmainfy.com/blog/summary-of-ksum-problems.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/946495
推荐阅读
相关标签
  

闽ICP备14008679号