题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
先排序,以便去重,然后采用递归求解
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Arrays.sort(num);
System.out.println("num = " + Arrays.toString(num));
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
threeSum(num,0,0,ans,temp);
return ans;
}
public void threeSum(int[] nums, int pos, int target, ArrayList<ArrayList<Integer>> ans,ArrayList<Integer> temp){
//三个数之和,同理若temp.size()==4表示求4个数之和
if(temp.size()==3){
if(target==0){
//列表需要新建,由于是引用,所以不能直接添加
ans.add(new ArrayList<>(temp));
}
return;
}
// 可缺省
// if(pos==nums.length){
// return;
// }
for(int i=pos;i<nums.length;i++){
temp.add(nums[i]);
threeSum(nums,i+1,target+nums[i],ans,temp);
temp.remove(temp.size()-1);
while((i+1)<nums.length && nums[i]==nums[i+1]){
i += 1;
}
}
}

查看2道真题和解析