Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
首先看到这道题脑子一热就想着用回溯方法很快能解决,如果加上剪枝应该可以AC,可是由于测试案例中有特别长的数组,导致递归调用很多层效率极度下降始终无法AC,除了效率问题,回溯去做没有很好解决重复解的问题,生硬的去重复估计也消耗不少时间,还是贴出超时代码。代码中包含了自己测试程序部分。
package Three_Sum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> ls = new ArrayList<List<Integer>>();
boolean [] flag = new boolean[num.length];
search(num, ls,flag,0);
Set<List<Integer>> set = new HashSet<>();
for(int i=0;i<ls.size();i++){
set.add(ls.get(i));
}
ls.clear();
Iterator<List<Integer>> it = set.iterator();
while(it.hasNext()){
ls.add(it.next());
}
return ls;
}
public void search(int[] num , List<List<Integer>> ls,boolean [] flag,int index){
//进行剪枝,如果已经超过sum就返回。
if(partofSum(flag, num, index))
return ;
if(countNum(flag) == 3){
List<Integer> ans = new ArrayList<>();
int sum = 0;
for(int i=0;i<flag.length;i++){
if(flag[i]){
sum += num[i];
if(sum>0)
return ;
}
}
if(sum ==0){
for(int i=0;i<flag.length;i++){
if(flag[i])
ans.add(num[i]);
}
ls.add(ans);
}
}
else {
for(int i=index;i<num.length;i++){
flag[i] = true;
search(num,ls,flag,i+1);
flag[i] = false;
}
}
}
public boolean partofSum(boolean []flag,int []num,int index){
int sum = 0;
for(int i=0;i<index;i++){
if(flag[i])
sum+=num[i];
}
if(sum>0)
return true;
else {
return false;
}
}
public int countNum(boolean[]flag){
int count = 0;
for(int i=0;i<flag.length;i++){
if(flag[i])
count++;
}
return count;
}
public static void main(String[] args) {
long startTime=System.nanoTime();
int [] num = {-9,-14,-3,2,0,-11,-5,11,5,-5,4,-4,5,-15,14,-8,-11,10,-6,1,-14,-12,-13,-11,9,-7,-2,-13,2,2,-15,1,3,-3,-12,-12,1,-2,6,14,0,-4,-13,-10,-12,8,-2,-8,3,-1,8,4,-6,2,1,10,2,14,4,12,1,4,-2,11,9,-7,6,-13,7,-3,8,14,8,10,12,11,-4,-13,10,14,1,-4,-4,2,5,4,-11,-7,3,8,-10,11,-11,-5,7,13,3,-2,8,-13,2,1,9,-12,-11,6};
Solution s = new Solution();
List<List<Integer>> ls = s.threeSum(num);
System.out.println(ls);
long endTime=System.nanoTime();
System.out.println("times: "+(endTime-startTime)+" ns");
}
}
最长测试案例耗时:times: 51734059 ns ,如果多组测试案例导致程序结果很慢。
更换思路:题目要求计算三个数和满足某个值,其实前面已经遇到过数组中两个元素值等于给定值(http://blog.csdn.net/huruzun/article/details/38639423),其实通过适当转换就到两个元素值等于给定值问题。
但是其中也有一些小的细节需要注意。
我们可以在 2sum问题 的基础上来解决3sum问题,假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2....An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> ls = new ArrayList<>(); int target = 0; Arrays.sort(num); for(int i=0;i<num.length-2;i++){ if(i>0&&num[i-1]==num[i]){ continue; } target = 0 - num[i]; twoSum(i+1, ls, num, target); } return ls; } public void twoSum(int index,List<List<Integer>> ls,int[]num,int target){ int head = index; int tail = num.length-1; while(head<tail){ if(num[head]+num[tail]>target){ tail--; }else if(num[head]+num[tail]<target){ head++; }else { List<Integer> ans = new ArrayList<>(); ans.add(num[index-1]); ans.add(num[head]); ans.add(num[tail]); ls.add(ans); int k = head+1; //去除重复问题 while(k<tail&&num[k]==num[head]) k++; head = k; k = tail -1; while(head<tail&&num[k]==num[tail]) k--; tail = k; } } } }
关于这个问题扩展下面这篇博文讲的挺好:http://www.cnblogs.com/TenosDoIt/p/3649607.html