【Leetcode】18. 4Sum 给定数组中的4个元素之和等于给定值的所有组合

1. 题目

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

2. 思路

和3 Sum closeset一样的,只是多遍历了一层。

3. 代码

耗时:123ms

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;
        int size = nums.size();
        switch(size) {
            case 0: 
            case 1:
            case 2:
            case 3:
                return ret;
        }
        sort(nums.begin(), nums.end());
        for (int i = 0; i < size - 3; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            for (int j = i + 1; j < size - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j-1]) continue;
                int k = j + 1;
                int l = size - 1;
                while (k < l) {
                    int sum = nums[i] + nums[j] + nums[k] + nums[l];
                    if (sum == target) {
                        bool same = false;
                        if (ret.size() > 0) {
                            vector<int>& last = ret[ret.size() - 1];
                            if (last[0] == nums[i] && last[1] == nums[j] && last[2] == nums[k] && last[3] == nums[l]) {
                                same = true;
                            }
                        }
                        if (!same) {
                            vector<int> got;
                            got.push_back(nums[i]);
                            got.push_back(nums[j]);
                            got.push_back(nums[k]);
                            got.push_back(nums[l]);
                            ret.push_back(got);
                        }
                        k++;
                        while(k < l && nums[k] == nums[k-1])k++;
                        l--;
                        while (k < l && nums[l] == nums[l+1])l--;
                    } else if (sum < target) {
                        k++;
                        while(k < l && nums[k] == nums[k-1])k++;
                    } else {
                        l--;
                        while (k < l && nums[l] == nums[l+1])l--;
                    }
                }
            }
        }
        return ret;
    }
};                     
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007276138
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞