Leetcode–4Sum

The Problem:

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)

Notes:

  1. Fix two number first, look for the two sum up to a target. The n-sum questions all follow the same idea, break down to two sum. See 3 Sum.

Java Solution:

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        ArrayList<ArrayList<Integer>> result = new  ArrayList<ArrayList<Integer>>();
        HashSet<String> set = new HashSet<String>(); // ---!!!!---use set to store result, remove duplicate
        if(num==null || num.length < 4)return (List)result; 
        Arrays.sort(num);
        int len = num.length;
        for(int s1 = 0; s1<len; s1++){ // ---!!!!!!-----four numbers are in order, inner loop start from the outter loop index +1
            for(int s2 = s1+1; s2<len; s2++){
                int i = s2+1;
                int j = len-1;
                int tar = target - num[s1] - num[s2];
                while(i<j){
                    if(num[i] + num[j] == tar){
                        String str = ""+num[s1]+num[s2]+num[i]+num[j];
                        if(!set.contains(str)){
                            ArrayList<Integer> one = new ArrayList<Integer>();
                            one.add(num[s1]);
                            one.add(num[s2]);
                            one.add(num[i]);
                            one.add(num[j]);
                            result.add(one);
                            set.add(str);
                            
                        }
                        i++;  //------!!!!!!!---if already get a target, i and j move at same time, 
                                    //          since only change i or j cannot produce same sum target
                        j--;
                    }
                    else if(num[i] + num[j] < tar)
                        i++;    // smaller then move right
                    else
                        j--;
                }
            }
        }
        return (List)result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s