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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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个指针同时进行,并且根据结果来移动两个指针,比如若是4个数的结果比target大,说明,应当将第二个指针往前移。也要进行去重!
代码如下:(参考了网上的资料,可以采用分治法,将所有两个数的组合的结果储存起来,然后再进行任意两个数的组合!!!后面再尝试写一下,估计会用到hash来记录对应的元素?)
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 6 class Solution { 7 private: 8 vector<vector<int>> res; 9 public: 10 vector<vector<int>> fourSum(vector<int>& nums, int target) { 11 int len = nums.size(); 12 13 sort(nums.begin(), nums.end()); 14 15 for (int i = 0; i < nums.size(); ++i) 16 { 17 18 for (int j = nums.size() - 1; j>i; --j) 19 { 20 21 helper(nums, target, i, j); 22 23 while (nums[j - 1] == nums[j])//去重 24 --j; 25 } 26 while (i<len-1&&nums[i + 1] == nums[i])//去重 27 ++i; 28 } 29 return res; 30 } 31 void helper(vector<int>&nums, int target, int index1, int index2) 32 { 33 int sum; 34 35 for (int i = index1 + 1,j=index2-1; i < j; ) 36 { 37 sum = nums[index1] + nums[index2] + nums[i] + nums[j];//进行比较,这是比较常用的做法来一次完成里面的遍历 38 if (sum == target) 39 { 40 vector<int> temp; 41 temp.push_back(nums[index1]); 42 temp.push_back(nums[i]); 43 temp.push_back(nums[j]); 44 temp.push_back(nums[index2]); 45 res.push_back(temp); 46 while (nums[i + 1] == nums[i] && i < j)//去重 47 i++; 48 while (nums[j - 1] == nums[j] && i < j)//去重 49 --j; 50 ++i; 51 --j; 52 } 53 else if (sum < target) 54 ++i; 55 else --j; 56 57 } 58 } 59 }; 60 61 int main() 62 { 63 Solution test; 64 vector<int> val = { -1,0,1,2,-1,-4}; 65 //for (int i = 0; i < val.size(); ++i) 66 // cout << val[i] << " "; 67 //cout << endl; 68 vector<vector<int>> result = test.fourSum(val, -1); 69 for (int i = 0; i < result.size(); ++i) 70 { 71 72 for (int j = 0; j < result[i].size(); ++j) 73 cout << result[i][j] << " "; 74 cout << endl; 75 } 76 77 return 0; 78 }
时间: 2024-10-28 06:17:44