题目链接:https://leetcode.com/problems/4sum/
解题思路:
和3sum一样,不过固定前两个数而已。
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); if(nums.length<4 || nums==null) return res; HashSet<ArrayList<Integer>> hs = new HashSet<>(); Arrays.sort(nums); for(int i=0;i<=nums.length-4;i++) { for(int j=i+1;j<=nums.length-3;j++) { int low = j+1; int high = nums.length-1; while(low < high) { int sum = nums[i]+nums[j]+nums[low]+nums[high]; if(sum==target) { ArrayList<Integer> un = new ArrayList<Integer>(); un.add(nums[i]); un.add(nums[j]); un.add(nums[low]); un.add(nums[high]); if(!hs.contains(un)) { res.add(un); hs.add(un); } low++; high--; } else if(sum>target) { high--; } else if(sum<target) { low++; } } } } return res; } }