题目链接
思路参考三数之和–链接
解法
class Solution {
public List < List < Integer > > fourSum ( int [ ] nums, int target) {
int n= nums. length;
int fourth;
Arrays . sort ( nums) ;
int target2;
List < List < Integer > > list= new ArrayList < > ( ) ;
for ( int first= 0 ; first< n; first++ ) {
if ( first> 0 && nums[ first] == nums[ first- 1 ] ) {
continue ;
}
for ( int second= first+ 1 ; second< n; second++ ) {
if ( second> first+ 1 && nums[ second] == nums[ second- 1 ] ) {
continue ;
}
fourth= n- 1 ;
target2= target- nums[ first] - nums[ second] ;
for ( int third= second+ 1 ; third< n; third++ ) {
if ( third> second+ 1 && nums[ third] == nums[ third- 1 ] ) {
continue ;
}
while ( third< fourth && nums[ third] + nums[ fourth] > target2) {
fourth-- ;
}
if ( third== fourth) {
break ;
}
if ( nums[ third] + nums[ fourth] == target2) {
List < Integer > a= new ArrayList ( ) ;
a. add ( nums[ first] ) ;
a. add ( nums[ second] ) ;
a. add ( nums[ third] ) ;
a. add ( nums[ fourth] ) ;
list. add ( a) ;
}
}
}
}
return list;
}
}