题目:
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)
翻译:
给定一个整形数组,找出4个数字使得他们的和加起来等于target。
思路:
和3Sum差不多。遍历,保存当前,找到其余三个数值和为target - num[i],然后剩下在用3SUM思路去解决。
代码:
public class Solution {
public static ArrayList<ArrayList<Integer>> fourSum(int[] nums, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(nums == null || nums.length < 4)
return res;
Arrays.sort(nums);
for(int i = 0; i < nums.length -3;i++)
{
if(i > 0 && nums[i] == nums[i-1])
continue;
ArrayList<ArrayList<Integer>> cur = threeSum(nums,i+1,target-nums[i]); //得到当前数字可以组合出来的数字序列的子集。
for(int j = 0 ;j < cur.size();j++)
{
cur.get(j).add(0, nums[i]);
}
res.addAll(cur);
}
return res;
}
public static ArrayList<ArrayList<Integer>> threeSum(int[] num,int start,int target)
{
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num == null||num.length<3)//如果只有2个数字 或者为空 返回空
return res;
//Arrays.sort(num);
for(int i = start; i<num.length -2;i++)// 保证最后得有num.length-1 和num.length-2两个数,才可以进循环
{
if(i > start && num[i] == num[i-1])
continue;
ArrayList<ArrayList<Integer>> cur = twoSum(num,i+1,target-num[i]); //得到当前数字可以组合出来的数字序列的子集。
res.addAll(cur);
}
return res;
}
public static ArrayList<ArrayList<Integer>>twoSum (int []num,int start,int target)
{
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num == null||num.length < 2)
return res;
int l = start;//起始位置
int pri = start-1;//当前数字
int r = num.length-1;//终止位置
while(l < r)//采用夹逼,逼近target
{
if(num[l]+num[r] == target)//
{
ArrayList<Integer> te = new ArrayList<Integer>();//符合的话 把三个数放入到list中
te.add(num[pri]);
te.add(num[l]);
te.add(num[r]);
res.add(te);
int k = l + 1;//从l的下一个开始 去除重复。
while(k < r&& num[k] == num[l])
k++;
l = k;
k = r - 1;//去除R的重复
while(k > l &&num[k] == num[r])
k--;
r = k;
}
else if(num[l] + num[r] > target)//夹逼
r--;
else l++;
}
return res;
}
}
碰到的问题就是在提交的时候,[-2,0,1,-3]和[-3,-2,0,1]竟然不是一样的结果。
明明是一样的数组。后来才发现在
for(int j = 0 ;j < cur.size();j++)
{
cur.get(j).add(0, nums[i]);
}
res.addAll(cur);
这个位置的时候,原来的写法是cur.get(j).add(nums[i]),后来改为上面的写法,把最小的数值插在最前面。
这样提交就OK了。