1+ /*
2+ Author: King, wangjingui@outlook.com
3+ Date: Dec 20, 2014
4+ Problem: 4Sum
5+ Difficulty: Medium
6+ Source: https://oj.leetcode.com/problems/4sum/
7+ Notes:
8+ Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
9+ Find all unique triplets in the array which gives the sum of zero.
10+ Note:
11+ Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
12+ Find all unique quadruplets in the array which gives the sum of target.
13+ Note:
14+ Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d)
15+ The solution set must not contain duplicate quadruplets.
16+ For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
17+ A solution set is:
18+ (-1, 0, 0, 1)
19+ (-2, -1, 1, 2)
20+ (-2, 0, 0, 2)
21+
22+ Solution: Similar to 3Sum, 2Sum.
23+ */
24+
25+ public class Solution {
26+ public List <List <Integer >> fourSum (int [] num , int target ) {
27+ int N = num .length ;
28+ List <List <Integer >> res = new ArrayList <List <Integer >>();
29+ if (N < 4 ) return res ;
30+ Arrays .sort (num );
31+ for (int i = 0 ; i < N ; ++i )
32+ {
33+ if (i > 0 && num [i ] == num [i -1 ]) continue ; // avoid duplicates
34+ for (int j = i +1 ; j < N ; ++j )
35+ {
36+ if (j > i +1 && num [j ] == num [j -1 ]) continue ; // avoid duplicates
37+ int twosum = target - num [i ] - num [j ];
38+ int l = j + 1 , r = N - 1 ;
39+ while (l < r )
40+ {
41+ int sum = num [l ] + num [r ];
42+ if (sum == twosum ) {
43+ ArrayList <Integer > tmp = new ArrayList <Integer >();
44+ tmp .add (num [i ]); tmp .add (num [j ]); tmp .add (num [l ]); tmp .add (num [r ]);
45+ res .add (tmp );
46+ while (l < r && num [l +1 ] == num [l ]) l ++; // avoid duplicates
47+ while (l < r && num [r -1 ] == num [r ]) r --; // avoid duplicates
48+ l ++; r --;
49+ }
50+ else if (sum < twosum ) l ++;
51+ else r --;
52+ }
53+ }
54+ }
55+ return res ;
56+ }
57+ }
0 commit comments