首页 > 代码库 > 18. 4Sum

18. 4Sum

https://leetcode.com/problems/4sum/#/solutions

 

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (num==null || num.length==0) return res;
        Arrays.sort(num);
        
        int max = num[num.length-1];
        if (4 * num[0] > target || 4 * max < target)
            return res;
        
        for (int i=num.length-1; i>=3; i--) {
            if (i<num.length-1 && num[i]==num[i+1]) continue;
            threeSum(0, i-1, num, target-num[i], res, num[i]);
        }
        return res;
    }
    
    public void threeSum(int start, int end, int[] num, int target, List<List<Integer>> res, int last1) {
        for (int i=end; i>=2; i--) {
            if (i<end && num[i]==num[i+1]) continue;
            twoSum(0, i-1, num, target-num[i], res, num[i], last1);
        }
    }
    
    public void twoSum(int l, int r, int[] num, int target, List<List<Integer>> res, int last2, int last1) {
        while (l < r) {
            if (num[l]+num[r] == target) {
                List<Integer> set = new ArrayList<Integer>();
                set.add(num[l]);
                set.add(num[r]);
                set.add(last2);
                set.add(last1);
                res.add(new ArrayList<Integer>(set));
                l++;
                r--;
                while (l<r && num[l] == num[l-1]) {
                    l++;
                }
                while (l<r && num[r] == num[r+1]) {
                    r--;
                }
            }
            else if (num[l]+num[r] < target) {
                l++;
            }
            else {
                r--;
            }
        }
    }
}

  

18. 4Sum