版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/88885481
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
样例
例1:
输入:[2,7,11,15]
输出:[]
例2:
输入:[-1,0,1,2,-1,-4]
输出:[[-1, 0, 1],[-1, -1, 2]]
注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
解题思路:
public class Solution {
/**
* @param numbers: Give an array numbers of n integer
* @return: Find all unique triplets in the array which gives the sum of zero.
*/
public List<List<Integer>> threeSum(int[] numbers) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(numbers);
dfs(numbers, new ArrayList<Integer>(), res, 0);
return res;
}
private void dfs(int[] a, List<Integer> list, List<List<Integer>> res, int index){
if(list.size() == 3){
int tmp = 0;
for(int i=0; i<list.size(); i++)
tmp += list.get(i);
if(tmp == 0){
res.add(new ArrayList<Integer>(list));
}
return;
}
for(int i = index; i < a.length; i++){
if(i != index && a[i] == a[i-1])
continue;
list.add(a[i]);
dfs(a, list, res, i + 1);
list.remove(list.size() - 1);
}
}
}