参考derrantcm的博客:网址:https://blog.csdn.net/DERRANTCM/article/details/46980229
package algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/*
参考derrantcm的博客:网址:https://blog.csdn.net/DERRANTCM/article/details/46980229
* 三个数的和
*
原题
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)
题目大意
给定一个n个元素的数组,是否存在a,b,c三个元素,使用得a+b+c=0,找出所有符合这个条件的三元组。
解题思路
可以在 2sum问题 的基础上来解决3sum问题,假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。
如A1,A2,A3,A4,,,An,则选择A1,只需在[A2,An]中2个数之和为0-A1既可。
A2,在[A3,An]中选择
* */
public class ThreeSum {
//如A1,A2,A3,A4,,,An,则选择A1,只需在[A2,An]中2个数之和为0-A1既可。
//A2,在[A3,An]中选择
public static List<List<Integer>> sumToZero(int[] array){
if(array==null||array.length<=2){
return null;
}
printArray(array);
//*************先对数组进行排序
Arrays.sort(array); //排序后
printArray(array);
List<List<Integer>> result= new LinkedList<List<Integer>>();
int length=array.length;
for(int i=0;i<length-2;i++){
int tmp=0-array[i];
List<Integer> list=new ArrayList<Integer>();
for(int j=i+1;j<length-1;j++){
int k=j+1;
while(k<length){
if(array[j]+array[k]==tmp){
System.out.println("值为0,A["+i+"]="+array[i]+",A["+j+"]="+array[j]+",A["+k+"]="+array[k]+"----{"+array[i]+","+array[j]+","+array[k]+"}");
list.add(array[i]);
list.add(array[j]);
list.add(array[k]);
result.add(list);
}
k++;
}
}
}
return result;
}
//输出数组
public static void printArray(int[] array){
if(array!=null){
for(int i=0;i<array.length;i++){
System.out.print(array[i]+",");
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array={-1,0,1,2,-1,-4};
sumToZero(array);
}
}