18. 4Sum

Description

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]
]

Solution

  • 排序夹逼法
    和15. 3Sum类似,只不过多加了一层循环而已,要保证结果不重复
vector<vector<int> > fourSum(vector<int> &nums, int target) {  
    vector<vector<int> > ret;
    if (nums.size() < 4) {
        return ret;
    }
    sort(nums.begin(), nums.end());
    for (int i = 0; i < nums.size() - 3; ++i) {
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        for (int j = i + 1; j < nums.size() - 2; ++j) {
            if (j > i + 1 && nums[j] == nums[j - 1]) {
                continue;
            }
            int s = j + 1, t = nums.size() - 1, curTarget = target -(nums[i] + nums[j]);
            while (s < t) {
                //cout<<nums[s]<<nums[t]<<target<<endl;
                if (nums[s] + nums[t] < curTarget) {
                    s++;
                } else if (nums[s] + nums[t] > curTarget) {
                    t--;
                } else {
                    ret.push_back({nums[i], nums[j], nums[s], nums[t]});
                    while (s < t && nums[s] == nums[s + 1]) {
                        s++;
                    }
                    while (t > s && nums[t] == nums[t - 1]) {
                        t--;
                    }
                    s++;
                    t--;
                }
            }
        }
    }
    return ret;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容