【中等】18-四数之和 4Sum

题目

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

Example:

Given array nums = [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]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum

解法

方法:双指针

解题思路

三数之和思路相同,多加一层遍历。

代码

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        int size = nums.size();
        if(size < 4) return res;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < size-3; ++i){
            if(i>0&&nums[i]==nums[i-1]) continue;
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+1]>target) break;
            if(nums[i]+nums[size-1]+nums[size-2]+nums[size-3]<target) continue;
            for(int j = i+1; j < size-2; ++j){
                if(j>i+1&&nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+2]+nums[j+1]>target) break;
                if(nums[i]+nums[size-1]+nums[size-2]+nums[j]<target) continue;
                int t = target-nums[i]-nums[j];
                int start = j+1, end = size-1;
                cout << start << end;
                while(start < end){
                    if(nums[start]+nums[end] < t) ++start;
                    else if(nums[start]+nums[end] > t) --end;
                    else{
                        res.push_back(vector<int>{nums[i], nums[j], nums[start], nums[end]});
                        start++;
                        end--;
                        while(start < end && nums[start] == nums[start-1]) ++start;
                        while(start < end && nums[end] == nums[end+1]) --end;
                    }
                }
            }
        }
        return res;
    }
};

总结

  1. 剪枝操作能够很大程度上提升速度
posted @ 2020-04-23 19:09  陌良  阅读(115)  评论(0编辑  收藏  举报