LeetCode K 个数之和

105 阅读1分钟

    public static List<List<Integer>> kSum(int[] nums, int target, int k) {
        if (nums == null || nums.length < k) {
            return null;
        }

        Arrays.sort(nums);
        List<List<Integer>> res = new LinkedList<>();
        List<Integer> path = new LinkedList<>();
        dfs(nums, 0, k, target, res, path);

        return res;

    }

    public static void dfs(int[] nums, int startIndex, int k, int remain, List<List<Integer>> res, List<Integer> path) {


        if (k == 2) {
            int i = startIndex, j = nums.length - 1;
            while (i < j) {
                //find a pair
                if (remain - nums[i] == nums[j]) {
                    List<Integer> temp = new ArrayList<>(path);
                    temp.add(nums[i]);
                    temp.add(remain - nums[i]);
                    res.add(temp);
                    //skip duplication
                    while (i < j && nums[i] == nums[i + 1]) i++;
                    while (i < j && nums[j - 1] == nums[j]) j--;
                    i++;
                    j--;
                    //move left bound
                } else if (remain - nums[i] > nums[j]) {
                    i++;
                    //move right bound
                } else {
                    j--;
                }
            }
            return;
        }
        for (int i = startIndex; i < nums.length - k + 1; i++) {

           /* if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }*/

            path.add(nums[i]);

            dfs(nums, i + 1, k - 1, remain - nums[i], res, path);

            path.remove(path.size() - 1);


        }

    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        return kSum(nums, target, 4);
    }