o(n^3)
固定一个数字 然后就变成3sum 再固定一个就是2sum
但是注意处理duplicate 就是四个数字都要避免dup 处理了四个地方
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>> (); if ( nums == null ) return res; Arrays.sort ( nums ); for ( int i = 0; i <= nums.length - 4; i ++ ){ int target3 = target - nums [ i ]; for ( int j = i + 1; j <= nums.length - 3; j ++ ){ int target2 = target3 - nums[ j ]; int head = j + 1; int tail = nums.length - 1; while ( head < tail ){ if ( nums [ head ] + nums[ tail ] < target2 ) head ++; else if ( nums [ head ] + nums [ tail ] > target2 ) tail --; else{ List<Integer> four = new ArrayList<Integer> (); four.add ( nums [ i ] ); four.add ( nums [ j ] ); four.add ( nums [ head ] ); four.add ( nums [ tail ] ); res.add ( four ); while ( head < tail && nums[ head ] == four.get ( 2 ) ) head ++; while ( head < tail && nums [ tail ] == four.get ( 3 ) ) tail --; } } while ( j + 1 <= nums.length - 3 && nums [ j + 1 ] == nums [ j ] ) j ++; } while ( i + 1 <= nums.length - 4 && nums [ i + 1 ] == nums [ i ] ) i ++; } return res; } }