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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章