leetcode15_三数之和

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> combine = new ArrayList<>();
    dfs(nums, ans, combine, 0);
    return drop_duplicate(ans);
}
private List<List<Integer>> drop_duplicate(List<List<Integer>> ans) {
    List<int[]> arrs = new LinkedList<>();
    for(List<Integer> list:ans) {
        int[] tmp = list.stream().mapToInt(Integer::intValue).toArray();
        Arrays.sort(tmp);
        boolean flag = false;
        for(int [] a: arrs) {
            if (Arrays.equals(a, tmp)) flag = true;
        }
        if(!flag)arrs.add(tmp);
    }
   // System.out.println(set);
    ans = new ArrayList<>();
    for(int[] arr: arrs) {
        List<Integer> list = new ArrayList<>();
        for(int a:arr) list.add(a);
        ans.add(list);
    }
    return ans;
}
private void dfs(int[] nums, List<List<Integer>> ans, List<Integer> combine, int idx) {
    if(combine.size() == 3) {
        int sum = 0;
        for(Integer a: combine) sum += a;
        if(sum == 0) ans.add(new ArrayList<>(combine));
    }
    if(idx == nums.length) {
        return;
    }

    dfs(nums, ans, combine, idx+1);
    combine.add(nums[idx]);
    dfs(nums, ans, combine, idx+1);
    combine.remove(combine.size()-1);
    return;
}
posted @ 2022-02-06 21:42  明卿册  阅读(18)  评论(0编辑  收藏  举报