給你一個包含 n 個整數的數組 nums
,判斷 nums
中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4], 滿足要求的三元組集合爲: [ [-1, 0, 1], [-1, -1, 2] ]
標準做法看了看解析 ,是用三指針去做的,只需要考慮全面一點,沒有什麼難度。
我是用了遞歸,超時了,可能受到之前寫全排列的影響,看到這道題,我首先就想去找三數的排列了😂,能寫出來超時的,我也很滿意😄,至少是對之前全排列的複習,記錄一下我的做法吧。
package test;
import java.util.*;
public class Test {
private List<List<Integer>> resLs = new ArrayList<>();
private Set<List> getOutput(int[] nums, LinkedList<Integer> ls, int sum, int []sign, int index, Set<List> set){
// 出口
if(ls.size() == 3 && sum == 0){
set.add(new LinkedList<>(ls));
return null;
}
// 剪枝,出口
if(ls.size() >= 3){
return null;
}
// 執行過程
for(int i = 0; i < nums.length; i++){
// i < index 每次只加後面的元素,忽略前面的元素,防止出現重複
if(sign[i] == 1 || i < index){
continue;
}
// 添加該元素
ls.addLast(nums[i]);
sign[i] = 1;
sum += nums[i];
getOutput(nums, ls, sum, sign, i, set);
// 出棧返回
ls.removeLast();
sign[i] = 0;
sum -= nums[i];
}
return set;
}
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<Integer> ls = new LinkedList<>();
int sign[] = new int[nums.length];
Set<List> set = new HashSet<>();
getOutput(nums, (LinkedList<Integer>) ls, 0, sign, 0, set);
for(List addLs: set){
resLs.add(addLs);
}
return resLs;
}
public static void main(String[] args) {
Test t = new Test();
List<List<Integer>> resLs = t.threeSum(new int[]{1, -1, -1, 0});
for(List<Integer>ls: resLs){
for(Integer a: ls){
System.out.print(a + " ");
}
System.out.println();
}
}
}