【组合&元素和问题】4Sum

来源:互联网 发布:php 执行exec 编辑:程序博客网 时间:2024/06/05 16:21

Given an array S of n integers, are there elements abc, 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)
第一反应:DFS,但是超时了,擦擦

public class Solution {    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        public void dfs(int [] num, ArrayList<Integer> l, int rs, int pos){        if(pos == num.length) return;                if(l.size() == 4){            res.add(l);            return ;        }        for(int i=pos; i<num.length; i++){            l.add(num[i]);            dfs(num, new ArrayList(l), rs - num[i], i+1);            l.remove(l.size()-1);        }    }        public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {        if(num == null) return null;        Arrays.sort(num);        ArrayList<Integer> l = new ArrayList<Integer>();        dfs(num, l, target, 0);        return res;    }}

解法二:将4个和转化成两个和问题(两个指针分两个方向指向数组)

三层for循环解决,O(n^3)

public class Solution {    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {        if(num == null) return null;        Arrays.sort(num);        int len = num.length;                for(int i=0; i<len; i++){            if(i!=0 && num[i]==num[i-1]) continue;                        for(int j=i+1; j<len; j++){                if(j!=i+1 && num[j]==num[j-1]) continue;                                int p = j+1, q = len - 1;                while(p < q){                    if(p!=j+1 && num[p]==num[p-1]){                        p++;                        continue;                    }                    if(q!=len-1 && num[q] == num[q+1]){                        q--;                        continue;                    }                                        int sum = num[i] + num[j] + num[p] + num[q];                    if(sum == target){                        ArrayList<Integer> l = new ArrayList<Integer>();                        l.add(num[i]);                        l.add(num[j]);                        l.add(num[p]);                        l.add(num[q]);                        res.add(l);                        p++;                    }                    else if(sum < target) p++;                    else q--;                }            }        }                return res;    }}



0 0