import java.util.ArrayList; import java.util.Arrays; public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if(num.length == 0){ return res; } //思路如下 第一步进行排序 Arrays.sort(num); //第二步 拿出一个数x 就变成从剩下的数中找两个数加起来等于x //第三步 在拿出一个数y 就变成从剩下的找一个数x + y+ 这个数 == 0了逐步拆解 for(int i = 0;i<num.length-2;i++){ int first = num[i]; for(int j = i + 1;j<num.length-1;j++){ int second = num[j]; for(int k = j + 1;k<num.length;k++){ int third = num[k]; if(first + second + third == 0){ ArrayList<Integer> item = new ArrayList<>(); item.add(first); item.add(second); item.add(third); if(!res.contains(item)){ res.add(item); } } } } } return res; } }