4Sum

来源:互联网 发布:彩虹六号 淘宝 编辑:程序博客网 时间:2024/06/04 17:47

题目:

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)
分析:

2-sum,3-sum,4-sum

http://blog.csdn.net/linhuanmars/article/details/24826871

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);    for(int i=num.length-1;i>2;i--)    {        if(i==num.length-1 || num[i]!=num[i+1])        {            ArrayList<ArrayList<Integer>> curRes = threeSum(num,i-1,target-num[i]);            for(int j=0;j<curRes.size();j++)            {                curRes.get(j).add(num[i]);            }            res.addAll(curRes);        }    }    return res;        }private ArrayList<ArrayList<Integer>> threeSum(int[] num, int end, int target){    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();    for(int i=end;i>1;i--)    {        if(i==end || num[i]!=num[i+1])        {            ArrayList<ArrayList<Integer>> curRes = twoSum(num,i-1,target-num[i]);            for(int j=0;j<curRes.size();j++)            {                curRes.get(j).add(num[i]);            }            res.addAll(curRes);        }    }    return res;}private ArrayList<ArrayList<Integer>> twoSum(int[] num, int end, int target){    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();    int l=0;    int r=end;    while(l<r)    {        if(num[l]+num[r]==target)        {            ArrayList<Integer> item = new ArrayList<Integer>();            item.add(num[l]);            item.add(num[r]);            res.add(item);            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)        {            r--;        }        else        {            l++;        }    }    return res;}}

还有一种解法,闲了再研究(*^__^*) ……


0 0
原创粉丝点击