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:
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)
题目的大概意思是:给定一个数组nums和一个整数target,在nums中找出四个数,使它们的和为target,找出所有这样的不重复的组合。
这道题难度等级:中等
思路:做法跟Two Sum、3 Sum、3 Sum Closest类似,也是使用枚举和夹逼。由于是4个数之和,复杂度会高一些O(n^3)。
1、先将数组排序(升序),再从第一个数开始枚举,遇到相同的跳过,直到最后一个,用k表示枚举第k个数;
2、从第k个枚举后面的数开始,用i表示后面的数;
3、左右夹逼:l、r表示从第i个数开始左右夹逼的下标。
4、在整个枚举和夹逼的过程中l<r始终成立,且要注意跳过一些已经处理过的数,不然会造成结果重复。
代码如下:
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); vector<vector<int> > res; vector<int> tmp(4, 0); int l, r, m; for (int k = 0; k < nums.size(); ++k){ //从第1个数开始枚举 if (k == 0 || nums[k] != nums[k - 1]){ //相同的跳过 for (int i = k + 1; i < nums.size(); ++i){ //从下一个数开始 l = i + 1; r = nums.size() - 1; //左右夹逼 while (l < r){ while (l < r && nums[k] + nums[i] + nums[l] + nums[r] > target){--r;}//限制右边界 if (l < r && nums[k] + nums[i] + nums[l] + nums[r] == target){ tmp[0] = nums[k]; tmp[1] = nums[i]; tmp[2] = nums[l]; tmp[3] = nums[r]; res.push_back(tmp); while(l < r && nums[l] == tmp[2]){++l;} } else{++l;} } m = i; while (nums[i] == tmp[1]){ m = i++; } i = m; } } } return res; } };提交代码 ,AC时间为Runtime: 128ms。